Пример #1
0
    def get(self, image=None):
        response = {}
        if image:
            groups = Group.objects(image=None)
        else:
            groups = Group.objects(image__ne=None)

        for group in groups:
            response[group.name] = {
                'full_name': group.full_name,
                'image': str(group.image.grid_id) if group.image.grid_id else None
                }

        return response
Пример #2
0
def get_current_group():
    '''
    Get the group pointed to by the settings object.  Settings is a singleton.
    If settings doesn't exist, create settings and group.
    '''
    if not Settings.objects.count():  # create settings and group if no settings object exists
        group = Group()
        group.save()
        settings = Settings(group=group)
        settings.save()
        return group
    settings = Settings.objects.all()[0]
    group = get_object_or_404(Group, id=settings.current_group_id)
    return group
Пример #3
0
def group_list(request):
    """
    List all gourps, or create a new group.
    """
    if request.method == 'GET':
        tasks = Group.objects.all()
        serializer = GroupSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        unique_name = request.data.get("unique_name")
        display_name = request.data.get("display_name")
        if unique_name and display_name:
            checkgoup = Group.objects.filter(unique_name=unique_name).first()
            if checkgoup:
                res = {
                    "code": 400,
                    "message": "Ops!, Unique name already exists"
                }
                return Response(data=res, status=400)
        else:
            res = {
                "code": 400,
                "message": "Ops!, Unique name and display name can't be null"
            }
            return Response(data=res, status=400)
        group = Group.create(unique_name, display_name)
        group.save()
        serializer = GroupSerializer(group, many=False)
        return JsonResponse(serializer.data, safe=False)
Пример #4
0
    def put(self, name=None):
        if not name:
            abort(404, message="A group name is required.")

        args = parser.parse_args()
        group = Group.objects(name__iexact=name).first()

        if not group:
            abort(404, message="A group with that name does not exist.")

        group.full_name=args['full_name']

        if args['image'] and validate_file(args['image'].filename):
            if group.image:
                group.image.replace(args['image'], content_type=args['image'].content_type)
            else:
                group.image.put(args['image'], content_type=args['image'].content_type)

        response = {
            'name': group.name,
            'full_name': group.full_name,
            'image': str(group.image.grid_id) if group.image.grid_id else None
        }

        group.save()

        return response
Пример #5
0
def insert_isolated_nodes_group(
        linked_groups: List[Group],
        isolated_nodes: List[int],
        pages: Dict[str, Page],
        table_to_original: Dict[int, str]
) -> List[Group]:
    """
    :param pages: original and full pages
    :type pages: Dict[str, Page]
    :param linked_groups:  graph vertices divided into groups with links to other groups
    :type linked_groups: List[Group]
    :param isolated_nodes: aliases of nodes with no incoming or outgoing nodes
    :type isolated_nodes: List[int]
    :param table_to_original: node alias - original node key pairs
    :type table_to_original: Dict[int, str]
    :return: the given list enriched with a special group containing only and all isolates
    :rtype: List[Group]
    """
    group_members = {}

    for node_alias in isolated_nodes:
        original_key = table_to_original.get(node_alias)
        full_node = pages.get(original_key)
        group_members[original_key] = full_node

    categories = create_categories_for_nodes([node for key, node in group_members.items()])

    if len(group_members) > 0:
        group = Group(id='isolates'+str(len(linked_groups)), members=group_members, categories=categories)
        linked_groups.append(group)

    return linked_groups
Пример #6
0
def group_list(request):
    """
    List all gourps, or create a new group.
    """
    if request.method == 'GET':
        tasks = Group.objects.all()
        serializer = GroupSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        unique_name = request.data.get("unique_name")
        display_name = request.data.get("display_name")
        if unique_name and display_name:
            checkgoup = Group.objects.filter(unique_name=unique_name).first()
            if checkgoup:
                res = {"code": 400,
                       "message": "Ops!, Unique name already exists"}
                return Response(data=res,
                                status=400)
        else:
            res = {"code": 400,
                   "message":
                   "Ops!, Unique name and display name can't be null"}
            return Response(data=res,
                            status=400)
        group = Group.create(unique_name, display_name)
        group.save()
        serializer = GroupSerializer(group, many=False)
        return JsonResponse(serializer.data, safe=False)
Пример #7
0
def make_group(group_id: str) -> Group:
    return Group(id=group_id,
                 links=[Link(link='0.3', occurrences=2)],
                 members={
                     oneUrl: make_page(oneUrl),
                     twoUrl: make_page(twoUrl)
                 },
                 categories=[Category(name='Social', occurrence=2)])
Пример #8
0
    def test_group_user_creation(self):
        group = Group(name='Group Test')
        group.save()
        user = User(
            name='Johannes',
            password='******',
            last_login=timezone.now(),
            email='*****@*****.**',
        )
        user.save()
        group_user = GroupUser(
            group=group,
            user=user
        )
        group_user.save()

        gu = GroupUser.objects.get(pk=group_user.pk)
        self.assertEqual(user.name, gu.user.name)
        self.assertEqual(group.name, gu.group.name)
Пример #9
0
    def create(self, request):
        """
        Função que cria um novo grupo

        Parameters:
        request (HttpRequest): : POST Request contendo o nome do grupo

        Returns:
        HttpResponse: Retorna o nome e id do grupo criado na resposta.

        """
        group_name = request.data['name']
        try:
            group = Group(name=group_name)
        except IntegrityError:
            return Response({'error': 'Group name alredy exists.'},
                            status=status.HTTP_406_NOT_ACCEPTABLE)
        group.save()
        response = GroupModelSerializer(group)
        return Response(data=response.data, status=status.HTTP_201_CREATED)
Пример #10
0
    def post(self):
        args = parser.parse_args()
        group = Group.objects(name__iexact=args['name']).first()
        if group:
            abort(409, message="A group with that name already exist.")

        group = Group(name=args['name'], full_name=args['full_name'])
        group.password = bcrypt.generate_password_hash(args['password'])

        if args['image'] and validate_file(args['image'].filename):
            group.image.put(args['image'], content_type=args['image'].content_type)

        group.save()

        response = {
            'name': group.name,
            'full_name': group.full_name,
            'image': str(group.image.grid_id) if group.image.grid_id else None
        }

        return response, 201
Пример #11
0
    def post(self):
        args = auth_parser.parse_args()
        name = args['username']
        password = args['password']

        group = Group.objects(name__iexact=name).first()

        if group:
            if bcrypt.check_password_hash(group.password, password):
                return {'Success': 'Group has been successfully authenticated.'}

        return {'Error': 'Invalid username or password.'}, 401
Пример #12
0
    def get(self, fullname=None):
        group = Group.objects(full_name__iexact=fullname).first()

        if not group:
            abort(404, message="A group with that name does not exist.")

        response = {
            'name': group.name,
            'full_name': group.full_name,
            'image': str(group.image.grid_id) if group.image.grid_id else None
        }

        return response
Пример #13
0
    def post(self, request):

        if request.data.get('type') == 'get':
            print("inside views post ", request.data)
            #For getting an individual group that a user is part of
            g = Group.objects.get(groupName=request.data.get('groupname'))
            m = MemberShip.objects.filter(group=g)
            m = m.values_list('person', flat=True)
            profiles = Profile.objects.filter(pk__in=m)
            jsonRes = serializers.serialize('json', profiles)
            #locations - all nearby locations to the midpoint of the group.
            locations = Location.objects.filter(group=g)
            locationsJson = serializers.serialize('json', locations)
            print('locations:', locationsJson)
            return Response({
                'members': jsonRes,
                'locations': locationsJson,
                'midpoint': g.midpoint
            })
        else:
            g = Group()
            #For creating a new group.
            print("inside views post ", request.data)
            g.groupName = request.data.get('groupname')
            g.save()
            p = Profile.objects.get(user=request.user)
            g.midpoint = getCoordinates(p.Location)
            m1 = MemberShip(group=g, person=p)
            m1.save()
            g.save()
            print('membership', m1, g.midpoint)
            #midpoint created of the creating users location.
            places = getPlaces(g.midpoint)
            print(places)
            #get locations close to them
            for place in places:
                l = Location(locationName=place['name'],
                             latLong=place['coordinates'],
                             rating=place['rating'],
                             types=place['types'],
                             group=g)
                l.save()
            serializer = GroupSerializer(g)
            l = Location.objects.filter(group=g)
            jsonRes = serializers.serialize('json', l.all())
            print("locations:", jsonRes)
            print('gorupL', serializer.data)
            return Response({'group': serializer.data, 'locations': jsonRes})
Пример #14
0
    def delete(self, name=None):
        if not name:
            abort(404, message="A group name is required.")
        group = Group.objects(name__iexact=name).first()

        if not group:
            abort(404, message="A group with that name does not exist.")

        if group.image:
            group.image.delete()

        group.delete()

        return {'success': "Group successfully deleted."}
Пример #15
0
    def post(self, request):
        context = get_nav_context(request)
        name = request.POST.get('group-name')
        description = request.POST.get('description')
        agents = request.POST.getlist('agent')
        modules = request.POST.getlist('module')
        if name:
            group = Group(name=name)
            group.save()
            for module in modules:
                module = Module.objects.get(uuid=module)
                group_module = Group_Module(group_id=group, module_id=module)
                group_module.save()
                command_string = {
                    "action": "add",
                    "module": {
                        "uuid": str(module.uuid),
                        "name": module.name,
                        "image": module.image
                    }
                }
                new_command = Command(cmd=json.dumps(command_string),
                                      group_id=group)
                new_command.save()
            for agent in agents:
                agent = Agent.objects.get(uuid=agent)
                agent_group = Agent_Group(agent_id=agent, group_id=group)
                agent_group.save()

                for module in modules:
                    module = Module.objects.get(uuid=module)
                    agent_module, created = Agent_Module.objects.get_or_create(
                        agent_id=agent, module_id=module)
                    agent_module.save()

        return render(request, template_name='index.html', context=context)
Пример #16
0
    def get(self, name=None):
        response = {}
        if name:
            group = Group.objects(name__iexact=name).first()

            if not group:
                abort(404, message="A group with that name does not exist.")

            response = {
                'name': group.name,
                'full_name': group.full_name,
                'image': str(group.image.grid_id) if group.image.grid_id else None
            }
        else:
            groups = Group.objects()

            for group in groups:
                response[group.name] = {
                    'full_name': group.full_name,
                    'image': str(group.image.grid_id) if group.image.grid_id else None

                }

        return response
Пример #17
0
    def get(self, name=None):
        if not name:
            abort(404, message="A group name is required.")

        group = Group.objects(name__iexact=name).first()

        if not group:
            abort(404, message="A group with that name does not exist.")

        response = {'members': {}}
        if group.members:
            for member in group.members:
                response['members'][member.id_no] = {
                    'name': member.name,
                }

        return response
Пример #18
0
def get_linked_groups_from_ids(pages: Dict[str, Page],
                               partition: Dict[str, int],
                               parent_group_id: str = None) -> List[Group]:
    """
    :param pages: the original pages from db
    :type pages: Dict[str, Page]
    :param partition: each page as the original page key with its respective group key
    :type partition:Dict[str, int]
    :param parent_group_id: the parent group key of which pages the subgroups will be created
    :type parent_group_id: str or None
    :return: a list of groups with links to original page keys
    :rtype: List[Group]
    """
    reversed_partition = reverse_partition(partition)
    groups_with_links, nodes_of_groups = get_links_and_nodes_of_groups(
        pages, reversed_partition)
    groups = []

    for group_id, g_nodes in nodes_of_groups.items():
        group_links: Dict[str, Link] = {}
        links = groups_with_links[group_id]
        parent_key_prefix = parent_group_id + "." if parent_group_id else ""
        if links is not None:
            for link in links:
                link_to_group = partition.get(link.link)
                whole_id = str(parent_key_prefix) + str(link_to_group)
                if link_to_group is not None and link_to_group != group_id:
                    if str(link_to_group) not in group_links:
                        new_link = Link(link=whole_id,
                                        occurrences=link.occurrences)
                        group_links[whole_id] = new_link
                    else:
                        group_links[whole_id].occurrences += link.occurrences

        whole_group_id = str(parent_key_prefix) + str(group_id)
        group_members = {node.url: node for node in g_nodes}
        categories = create_categories_for_nodes(g_nodes)

        group = Group(id=whole_group_id,
                      links=[group_links[key] for key in group_links],
                      members=group_members,
                      categories=categories)
        groups.append(group)

    return groups
Пример #19
0
def async_create_group(data):
    group_name = data['name']
    members = data['members']
    try:
        group = Group(name=group_name)
        memberships = []
        for member in members:
            group_membership = GroupMembership(user_id=member['id'])
            group_membership.group = group
            memberships.append(group_membership)

        db.session.add(group)
        for membership in memberships:
            db.session.add(membership)
    except Exception as err:
        raise err

    db.session.commit()
Пример #20
0
def inituser():
    db.create_all()
    try:
        group = Group(name='admin',
                      app_add=True,
                      app_edit_all=True,
                      app_edit_my=True,
                      app_drop=True,
                      user_add=True,
                      user_drop=False)
        db.session.add(group)
    except:
        pass
    try:
        hash = sha256_crypt.encrypt('admin')
        user = User(email='admin@intra', password_hash=hash, group_id=1)
        db.session.add(user)
    except:
        pass

    db.session.commit()
Пример #21
0
def group_member_processes(process, member_id_no=None, group_name=None):
    if not member_id_no:
        abort(404, message="An id number is required.")

    if not group_name:
        abort(404, message="A group name is required.")

    individual = Individual.objects(id_no=member_id_no).first()
    group = Group.objects(name__iexact=group_name).first()

    if not individual:
        abort(404, message="An individual with that id number does not exist.")

    if not group:
        abort(404, message="A group with that name does not exist.")

    if process == 'insert':
        individual.update(add_to_set__groups=[group])
        group.update(add_to_set__members=[individual])
    elif process == 'delete':
        individual.update(pull__groups=group)
        group.update(pull__members=individual)
Пример #22
0
 def test_group_creation(self):
     group = Group(name='Group Test')
     group.save()
     self.assertEqual(Group.objects.get(pk=group.pk).name, 'Group Test')
Пример #23
0
 def _init_Group(self):
     Group.create("source", "Source").save()
     Group.create("solr", "Solr").save()
     Group.create("other", "Other").save()
Пример #24
0
def make_custom_group(group_id: str, pages: Dict[str, Page], links: List[Link],
                      categories: List[Category]) -> Group:
    return Group(id=group_id,
                 links=links,
                 members=pages,
                 categories=categories)
Пример #25
0
    def post(self, request):
        check = CheckRequest(request);
        if check.admin:
            return JsonResponse({
                "status": "error",
                "msg": "User logined"
            })
        uf = JoinForm(check.jsonForm)
        if uf.is_valid():
            groupId = uf.cleaned_data['groupId']
            groupName = uf.cleaned_data['groupName']
            qq = uf.cleaned_data['qq']
            nick = uf.cleaned_data['nick']
            password = uf.cleaned_data['password']
            #检测群是否存在
            checkGroup = Group.objects.filter(groupId__exact = groupId).first()
            if checkGroup:
                if checkGroup.status == 0:
                    return JsonResponse({
                        "status" : 'error',
                        'msg' : "此群已被注册,但正在验证中,群ID:%s" % groupId
                    })
                elif checkGroup.status == 1:
                    return JsonResponse({
                        "status" : 'error',
                        'msg' : "此群已被注册并验证通过,可申请转让,群ID:%s" % groupId
                    })
                elif checkGroup.status == 2:
                    GroupAdmin.objects.filter(groupId__exact = groupId).delete()
                    checkGroup.delete()
                else:
                    return JsonResponse({
                        "status" : 'error',
                        'msg' : "此群已被注册"
                    })
            group = Group(
                groupId = groupId,
                groupName = groupName
            )
            group.save()
            if not group.id:
                return JsonResponse({
                    "status" : 'error',
                    'msg' : "Save group error:%s" % uf.cleaned_data['groupId']
                })

            admin = GroupAdmin(
                groupId = groupId,
                qq = qq,
                nick = nick,
                password = db_password(password),
                login_random = new_random(),
                activate_random = new_random(),
                recover_random = new_random(),
                userType = 1
                )
            admin.save()
            if admin.id:
                return JsonResponse({
                    "status" : 'success',
                    'msg' : "",
                    'data':{
                        'id': admin.id,
                        'groupId' : admin.groupId,
                        'qq' : admin.qq,
                        'nick' : admin.nick,
                        'userType': admin.userType
                    }
                })
            else:
                return JsonResponse({
                    "status" : 'error',
                    'msg' : "Admin save error"
                })

        else:
            return JsonResponse({
                "status" : 'error',
                'msg' : "Illegal post: %s" % uf.errors
            })
Пример #26
0
 def create_group(self):
     return Group()
Пример #27
0
    def post(self, request):
        check = CheckRequest(request)
        if check.admin:
            return JsonResponse({"status": "error", "msg": "User logined"})
        uf = JoinForm(check.jsonForm)
        if uf.is_valid():
            groupId = uf.cleaned_data['groupId']
            groupName = uf.cleaned_data['groupName']
            qq = uf.cleaned_data['qq']
            password = uf.cleaned_data['password']
            #检测群是否存在
            checkGroup = Group.objects.filter(groupId__exact=groupId).first()
            if checkGroup:
                if checkGroup.status == 0:
                    return JsonResponse({
                        "status": 'error',
                        'msg': "此群已被注册,但正在验证中,群ID:%s" % groupId
                    })
                elif checkGroup.status == 1:
                    return JsonResponse({
                        "status":
                        'error',
                        'msg':
                        "此群已被注册并验证通过,可申请转让,群ID:%s" % groupId
                    })
                elif checkGroup.status == 2:
                    GroupAdmin.objects.filter(groupId__exact=groupId).delete()
                    checkGroup.delete()
                else:
                    return JsonResponse({"status": 'error', 'msg': "此群已被注册"})
            group = Group(groupId=groupId, groupName=groupName)
            group.save()
            if not group.id:
                return JsonResponse({
                    "status":
                    'error',
                    'msg':
                    "Save group error:%s" % uf.cleaned_data['groupId']
                })

            admin = GroupAdmin(groupId=groupId,
                               qq=qq,
                               password=db_password(password),
                               login_random=new_random(),
                               activate_random=new_random(),
                               recover_random=new_random(),
                               userType=1)
            admin.save()
            if admin.id:
                return JsonResponse({"status": 'success', 'msg': ""})
            else:
                return JsonResponse({
                    "status": 'error',
                    'msg': "Admin save error"
                })

        else:
            return JsonResponse({
                "status": 'error',
                'msg': "Illegal post: %s" % uf.errors
            })
Пример #28
0
 def _init_Group(self):
     Group.create("youku", "Youku").save()
     Group.create("tudou", "Tudou").save()
     Group.create("aiqiyi", "Aiqiyi").save()