Example #1
0
def add_tag(req, person_stub='', tag='', category_slug='', is_ajax=False,
            redirect_to_tags_page=False):
    """
        adds a tag to a user if they do not have tagging turned off
    """
    if req.method == 'POST':
        if tag == '':
            tag = req.POST.get('tag', '').strip()
        if category_slug == '':
            category_slug = req.POST.get('tag_category_slug', '').strip()
        if tag == '':
            return json_response({'error':
                                 'Please enter a tag that is not blank.'})
        elif person_stub == '':
            return json_response({'error':
                                 'Person not found.'})
        person = Person.objects.get(stub=person_stub)
        # make sure tag does not already exist
        try:
            taggeditem = TaggedItem.objects.get(
                tag_category__slug=category_slug, object_id=person.id,
                tag__name__iexact=tag)
        except Exception:
            taggeditem = add_tags(person, tag, category_slug, req.user,
                                  'person')
            person.expire_cache()
            expire_cache_group('tags')

        url = reverse('staff_directory:person', args=[person.stub])
        if person.user != req.user:
            email_info = EmailInfo(
                subject='You were tagged in the staff directory!',
                text_template='staff_directory/email/user_tagged.txt',
                html_template='staff_directory/email/user_tagged.html',
                to_address=person.user.email,
            )
            # set notification
            title = '%s %s tagged you with "%s"' % \
                (req.user.first_name, req.user.last_name, tag)
            Notification.set_notification(req.user, req.user, "tagged", tag,
                                          person.user, title, url, email_info)
        if is_ajax:
            if redirect_to_tags_page:
                return json_response({'redirect':
                                       reverse('staff_directory:show_by_tag',
                                               args=[taggeditem.tag.slug])})
            return json_response({'redirect':
                                   reverse('staff_directory:person', args=[person.stub])})
        else:
            return HttpResponseRedirect(reverse('staff_directory:person',
                                                args=[person.stub]))
Example #2
0
def search_results_json(req, term='', context_models=''):
    all_results = []
    term = req.GET.get('term', '')
    context_models = req.GET.get('model', '').split(',')

    p = {}
    indexes = sorted(_get_indexes(),
                     key=lambda index: 0 if index[0].__name__.lower() in
                     context_models else index[1].PRIORITY)

    for index in indexes:
        results = SearchQuerySet().filter(content=term).models(index[0])
        results_count = results.count()
        for r in results[:5]:
            all_results.append(_create_category(r.display,
                                                r.index_name,
                                                term,
                                                r.model_name,
                                                r.url,
                                                results_count))

    all_results.append({'category': 'Wiki', 'term': term,
                        'search_slug': 'wiki'})

    return json_response(all_results)
Example #3
0
def system_status(request):
    status = {}

    for name, label in models.Status.NAME_CHOICES:
        status[name] = models.Status.GetValue(name)

    return json_response(status)
Example #4
0
    def test_wrap_httpresponse(self):
        testresp = HttpResponse('foo')

        def testfun(request):
            return testresp
        respfun = json_response(testfun)
        self.assertEqual(respfun(HttpRequest()), testresp)
    def wrap(request, *args, **kwargs):
        person = Person.objects.get(stub=request.POST.get('person_stub'))

        if person.user == request.user or person.allow_tagging:
            return f(request, *args, **kwargs)
        else:
            errMsg = person.user.first_name + " " + person.user.last_name + " has chosen not to allow tagging."
            return json_response({'error': errMsg})
Example #6
0
def add_result(request):
    car = request.user.core_user.car
    value = request.POST['value']
    sensor_pid = request.POST['sensor_pid']
    result_dt = request.POST['result_dt']

    params = {
        'sensor_id': sensor_pid,
        'car': car,
        'value': value,
        'result_dt': result_dt,
    }
    if models.SensorResult.objects.filter(**params).exists():
        return json_response("Already same result exists.")
    else:
        models.SensorResult.objects.create(**params)
        return json_response("Ok")
Example #7
0
def car_pc_service(request):
    user_name = request.POST['user_name']
    password = request.POST['password']

    models.Settings.SetValue(models.Settings.SERVICE_USER_NAME, user_name)
    models.Settings.SetValue(models.Settings.SERVICE_USER_PASSWORD, password, encrypt_it=True)

    return json_response('Ok')
 def setUp(self):
     def testfun(_, messages, userinfo):
         messages['success'] = True
         return {'messages': messages,
                 'user': userinfo.username}
     self.user = User.objects.create(
         username='******', email='*****@*****.**',
         password=_HASHED_DEFAULT_PASSWORD, token='testtoken')
     self.wrapped = api_token_required(json_response(testfun))
     self.request = HttpRequest()
     self.request.method = 'POST'
Example #9
0
File: video.py Project: dyus/car-pc
def start_upload(request):
    if 'start' in request.POST:
        uploading = models.Status.GetValue(models.Status.VIDEO_UPLOAD_STARTED)
        if uploading == '1':
            return json_response("Already uploading")

        # start upload
        models.Status.SetValue(models.Status.VIDEO_UPLOAD_STARTED, '1')
        models.Command.objects.create(command=models.Command.START_VIDEO_UPLOAD)

        capturing = models.Status.GetValue(models.Status.VIDEO_STARTED)
        if capturing == '1':
            # restart capturing
            models.Status.SetValue(models.Status.VIDEO_STARTED, '0')
            time.sleep(1)

        # start video
        models.Status.SetValue(models.Status.VIDEO_STARTED, '1')

        return json_response("Started")
Example #10
0
 def test_wrap_plain_function(self):
     def testfun(request):
         return ['bla']
     respfun = json_response(testfun)
     result = respfun(HttpRequest)
     self.assertIsInstance(result, HttpResponse)
     self.assertEqual(result['content-type'], 'text/json')
     self.assertEqual(
         json.loads(respfun(HttpRequest()).content),
         ['bla']
     )
Example #11
0
 def inner(request, *args, **kwargs):
     # for demonstration purpose, use plain username/password
     # in reality, this should be an API key or key/secret
     username = request.META.get("HTTP_API_USER")
     password = request.META.get("HTTP_API_USER_PASS")
     user = authenticate(username=username, password=password)
     if user:
         request.user = user
         return function(request, *args, **kwargs)
     else:
         return json_response({'error': _('Invalid account')})
Example #12
0
def tags(request):
    """
    Get exhaustive list of Tags for published Posts
    :return: tags [LIST] list of Post tags
    """
    # Grab all published Posts
    post_query = Post.query(ancestor=get_blog_key()).filter(Post.published == True)

    # Remove duplicates
    tags = list(set(flatten_list([post.tags for post in post_query.iter()])))

    return json_response(tags)
Example #13
0
def search_tags_json(req, term='', model=''):
    if req.method == 'POST':
        term = req.POST.get('term', '').strip()
        return HttpResponseRedirect(reverse('search:tags_json',
                                            args=[term, ]))
    elif req.method == 'GET':
        if term.strip() == '':
            term = req.GET.get('term', '').strip()
        q = _get_query(term, ['name', ])
        results = Tag.objects.filter(q)
        if model:
            # join with taggeditem may results in duplicates, requires distinct()
            results = results.filter(taggit_taggeditem_items__content_type__name=model).distinct()
        results = results[:5]
        results_json = []
        for r in results:
            results_json.append({'label': r.name, 'value': r.name})
        if len(results_json) > 0:
            return json_response(results_json)
        else:
            return json_response([{}])
Example #14
0
def search_persons_json(req):
    json_resp = []
    term = req.GET.get('term', '').strip()
    if term != '':
        q = _get_query(term, ['user__first_name', 'user__last_name'])
        matching_people = Person.objects.filter(q).filter(
            user__is_active=True).distinct()[:5]
        for person in matching_people:
            name = person.user.first_name + ' ' + person.user.last_name
            json_resp.append({'label': name, 'stub': person.stub,
                              'value': name})
    return json_response(json_resp)
Example #15
0
def users_by_division_json(req):
    result = {}
    divisions = OrgGroup.objects.filter(
        parent=None).exclude(title__icontains="Region").order_by('title')
    for d in divisions:
        result[d.title] = User.objects.filter(is_active=True).filter(
            Q(person__org_group=d) |
            Q(person__org_group__parent=d)).order_by(
            'last_name', 'first_name').count()
    result_json = []
    for k in result.keys():
        result_json.append({'name': k, 'value': result[k]})
    return json_response(result_json)
Example #16
0
def posts(request, post_id=None, tags=None, page=None, titles_only=False, published_only=False):
    """
    Get Published Blog Posts
    :param tags [LIST] of tags to filter on [optional]
    :param page [INT] page number of Posts to return [optional]
    :param titles_only [BOOLEAN] return Post titles and stamps only [optional]
    :param published_only [BOOLEAN] return published Posts only [optional]
    :param post_id [LONG] Post identifier [optional]
    :return: posts [LIST] List of Posts
    """
    # ID filter (if we get an ID parameter lets assume the user wants all the info on that Post)
    if post_id:
        post = Post.get_by_id(post_id, parent=get_blog_key())
        iterator = [post] if post else []
    else:
        # If no ID specified, get all Posts ordered by stamp for our Blog
        post_query = Post.query(ancestor=get_blog_key()).order(-Post.stamp)

        # Published filter
        if published_only:
            post_query = post_query.filter(Post.published == True)

        # Tag filter
        if tags:
            post_query = post_query.filter(Post.tags.IN(tags))

        # Page Filter
        if page is not None:
            iterator = post_query.fetch(POST_PAGE_SIZE, offset=page * POST_PAGE_SIZE)
        else:
            iterator = post_query.fetch()

    # Preview or full Post
    if titles_only:
        response = json_response([post.preview() for post in iterator])
    else:
        response = json_response([post.dictionary() for post in iterator])

    return response
Example #17
0
File: video.py Project: dyus/car-pc
def stop_upload(request):
    if 'stop' in request.POST:
        models.Status.SetValue(models.Status.VIDEO_UPLOAD_STARTED, '0')
        models.Command.objects.create(command=models.Command.STOP_VIDEO_UPLOAD)

        capturing = models.Status.GetValue(models.Status.VIDEO_STARTED)
        if capturing == '1':
            # restart capturing
            models.Status.SetValue(models.Status.VIDEO_STARTED, '0')
            time.sleep(1)
            models.Status.SetValue(models.Status.VIDEO_STARTED, capturing)

        return json_response("Stopped")
Example #18
0
def create(request):
    user_name = _gen_username()
    password = _gen_password()
    car_name = request.POST['name']
    car_description = request.POST.get('description', '')

    if models.Car.objects.filter(
        name=car_name,
        user__main_user__auth_user=request.user
    ).exists():
        err_msg = 'Car with name "%s" for user "%s" already exists.' % (car_name, request.user)
        return json_response({'error': err_msg}, status=400)

    auth_user = AuthUser.objects.create_user(username=user_name, password=password)
    user = models.User.objects.create(auth_user=auth_user, is_car=True, main_user=request.user.core_user)
    models.Car.objects.create(user=user, name=car_name, description=car_description)

    result = {
        'user_name': user_name,
        'password': password,
    }

    return json_response(result)
Example #19
0
File: video.py Project: dyus/car-pc
def devices(request):
    """
        list of video devices in system
    """
    result = []
    for device in models.VideoDevice.GetExistingDevices():
        result.append({
            'id': device.id,
            'dev_path': device.dev_path,
            'name': device.get_name(),
            'resolution': device.resolution,
            'available_resolutions': device.get_resolutions(),
            'is_uses': device.is_uses,
        })
    return json_response(result)
Example #20
0
File: movie.py Project: dyus/car-pc
def browse(request):
    result = []

    movies = glob.glob("%s/*.mp4" % settings.MOVIE_CONVERTED)
    for movie_path in movies:
        file_name = movie_path.split('/')[-1]

        file_size = os.path.getsize(movie_path)
        human_file_size = human_size(file_size)

        result.append({
            'name': file_name,
            'size': human_file_size,
        })

    return json_response(result)
Example #21
0
def last_results(request):
    import obd.models

    results = []
    for sensor in obd.models.Sensor.objects.all():
        if sensor.results.exclude(value__in=('', 'NO DATA')).exists():
            latest = sensor.results.exclude(value__in=('', 'NO DATA')).latest()
            results.append({
                'description': sensor.description,
                'pid': sensor.pid,
                'unit': sensor.unit,
                'value': latest.value,
                'date_time': latest.dc,
            })

    return json_response(results)
Example #22
0
def labour_admin_roster_job_category_fragment(request, vars, event, job_category):
    job_category = get_object_or_404(JobCategory, event=event, pk=job_category)

    vars.update(
        **labour_admin_roster_vars(request, event)
    )

    hours = vars['hours']

    vars.update(
        job_category=job_category,
        totals=[0 for i in hours],
    )

    return json_response(dict(
        replace='#jobcategory-{0}-placeholder'.format(job_category.pk),
        content=render_string(request, 'labour_admin_roster_job_category_fragment.jade', vars)
    ))
Example #23
0
File: video.py Project: dyus/car-pc
def set_device_resolution(request, id):
    models.VideoDevice.objects.filter(id=id).update(resolution=request.POST['resolution'])
    return json_response("Ok")
Example #24
0
File: video.py Project: dyus/car-pc
def set_device_uses(request, id):
    is_uses = int(request.POST['is_uses'])
    models.VideoDevice.objects.filter(id=id).update(is_uses=is_uses)
    return json_response("Ok")
Example #25
0
File: video.py Project: dyus/car-pc
def stop_capture(request):
    if 'stop' in request.POST:
        models.Status.SetValue(models.Status.VIDEO_STARTED, '0')
        return json_response("Stopped")
Example #26
0
File: video.py Project: dyus/car-pc
def start_capture(request):
    if 'start' in request.POST:
        models.Status.SetValue(models.Status.VIDEO_STARTED, '1')
        return json_response("Started")
Example #27
0
def halt(request):
    if 'halt' in request.POST:
        models.Command.objects.create(command=models.Command.SYSTEM_DOWN)
        return json_response("Ok")
Example #28
0
def json_error(error):
    return json_response({'error': error})