Пример #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]))
Пример #2
0
    def test_wrap_httpresponse(self):
        testresp = HttpResponse('foo')

        def testfun(request):
            return testresp
        respfun = json_response(testfun)
        self.assertEqual(respfun(HttpRequest()), testresp)
Пример #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)
Пример #4
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)
Пример #5
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)
Пример #6
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')
Пример #7
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")
Пример #8
0
    def test_wrap_httpresponse(self):
        testresp = HttpResponse('foo')

        def testfun(request):
            return testresp

        respfun = json_response(testfun)
        self.assertEqual(respfun(HttpRequest()), testresp)
Пример #9
0
    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})
Пример #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'])
Пример #11
0
def add_entry(request):
    """ Add a new blank entry to the book """
    #Return HttpResponseForbidden here as cleaner code? and elsewhere...
    if not request.is_ajax():
        return HttpResponseForbidden()

    if request.method != 'POST':
        return json_response({'success': False, 'error': 'wrong method'})

    form = NewEntryForm(request.POST)
    if form.is_valid():
        book = Book.objects.get(id=int(request.POST['book_id']))
        entry = Entry(title=form.cleaned_data['title'], book=book)
        entry.save()
        url = entry.get_absolute_url()

        return json_response({'success': True, 'url': url})
    else:
        return json_response({'success': False, 'error': 'missing argument'})
Пример #12
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')
Пример #13
0
 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'
Пример #14
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')})
Пример #15
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']
     )
Пример #16
0
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")
Пример #17
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)
Пример #18
0
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")
Пример #19
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)
Пример #20
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([{}])
Пример #21
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)
Пример #22
0
def get_number(request):

    try:
        if request.method == 'POST':
            number = request.POST[
                'number']  # MUST BE STRING => CASE int('021') -> 21 ('0' missing)
            rules = json.loads(request.POST['rules'])

            # Check rules (keys must be int)
            rules = {int(k): [i for i in v] for k, v in rules.items()}

            # Get words
            start_t = time.time()
            words_matched, total_lines, regex = get_words(number, mnemo=rules)
            end_t = time.time() - start_t

            # Prepare result
            res = '-----------------------------\n'
            res += '--        RAEFINDER        --\n'
            res += '-----------------------------\n'

            res += '\n'.join(words_matched)

            # Print results
            if len(words_matched):
                res += '\n\n'
                res += '-------------------------------\n'
                res += '- Words matched: {:,}\n'.format(len(words_matched))
                res += '- Words analyzed: {:,}\n'.format(total_lines)
                res += '- Elapsed time: %.5fs\n' % end_t
                res += '- Regex used: "%s"' % regex
            else:
                res += 'No words matched the expression'

            return json_response(msg=res)
        else:
            return json_response(msg='Invalid request', error=True)

    except Exception as e:
        return json_response(msg=str(e), error=True)
Пример #23
0
def edit_model_title(request, entry_id=None):
    """ Edit the name of an book or entry, depending which one is passed in"""
    if not request.is_ajax():
        return HttpResponseForbidden()

    #if request.method != 'POST':
    #   return json_response({'success': False, 'error': 'Should be a POST but is not'})

    #Get new title
    #new_title = request.POST.get('new_title', None)

    # If we are editing the book title
    #if book_id:

    #   try:
    #      book = Book.objects.get(id=(int(book_id)))

    #     if book.author != request.user:
    #         return HttpResponseForbidden()
    # except Book.DoesNotExist:
    #     return json_response({'success': False, 'error': 'Book not found'})

    # book.setTitle(new_title)

    #Otherwise we are editing the model title
    #else:
    try:
        entry = Entry.objects.get(id=int(entry_id))

        if entry.book.author != request.user:
            return HttpResponseForbidden()

    except Entry.DoesNotExist:
        return json_response({'success': False, 'error': 'Entry not found'})

    # Set new title to current entry title
    entry.setTitle(new_title)

    return json_response({'success': True})
Пример #24
0
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")
Пример #25
0
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")
Пример #26
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
Пример #27
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)
Пример #28
0
def unshare(request):
    if not request.is_ajax():
        return HttpResponseForbidden()

    if request.method != 'POST':
        return json_response({'success': False, 'error': 'wrong method'})

    shared = request.POST.get('shared', None)
    if not shared:
        return json_response({'success': False, 'error': 'missing argument'})

    try:
        shared_elem = Shared.objects.get(id=int(shared))
    except Shared.DoesNotExist:
        return json_response({'success': False, 'error': 'shared not found'})
    # Does this make sense? If they are both not you, then return a forbidden access?
    # Will only change if it does NOT work
    if shared_elem.from_user != request.user and shared_elem.to_user != request.user:
        return HttpResponseForbidden()

    shared_elem.delete()
    return json_response({'success': True})
Пример #29
0
    def setUp(self):
        def testfun(_, messages, userinfo):
            messages['success'] = True
            return {'messages': messages, 'user': userinfo.username}

        self.user = User.objects.create_user('testuser',
                                             '*****@*****.**',
                                             password=_TEST_PASSWORD,
                                             token='testtoken',
                                             is_active=True)
        self.wrapped = api_token_required(json_response(testfun))
        self.request = HttpRequest()
        self.request.method = 'POST'
Пример #30
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)
Пример #31
0
def delete_book(request):
    if not request.is_ajax():
        return HttpResponseForbidden()

    if request.method != 'POST':
        return json_response({'success': False, 'error': 'wrong method'})

    book = request.POST.get('book', None)
    if not book:
        return json_response({'success': False, 'error': 'missing argument'})

    try:
        delete_book = Book.objects.get(id=int(book))
    except Book.DoesNotExist:
        return json_response({'success': False, 'error': 'book not found'})

    if delete_book.author != request.user:
        return HttpResponseForbidden()
    """ Does it delete every entry also with the book itself? Do we have to do that or 
        Django take care of that for us? """
    delete_book.delete()

    return json_response({'success': True, 'url': reverse('core_home')})
Пример #32
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)
Пример #33
0
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)
Пример #34
0
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)
Пример #35
0
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)
Пример #36
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)
Пример #37
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)
Пример #38
0
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)
Пример #39
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)
    ))
Пример #40
0
def playlist(request):
    url = settings.VLC_HTTP + '/requests/playlist.xml'
    xml_tree = _get_xml(url)

    result = []
    items = _find_element(xml_tree, 'leaf')
    for el in items:
        duration_human = None
        if el.attrib.get('duration'):
            duration = el.attrib['duration']
            duration_human = _humanize_time(duration)

        result.append({
            'id': el.attrib.get('id'),
            'name': el.attrib.get('name'),
            'duration_sec': el.attrib.get('duration'),
            'duration_human': duration_human,
            'uri': el.attrib.get('uri'),
            'current': el.attrib.get('current'),
        })

    return json_response(result)
Пример #41
0
def set_current(request):
    card_name = request.POST['card_name']

    models.Settings.SetValue(models.Settings.AUDIO_CARD, card_name)

    return json_response('Ok')
Пример #42
0
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")
Пример #43
0
def list_cards(request):
    result = {}
    result['cards'] = audio_cards_list()
    return json_response(result)
Пример #44
0
def share_book(request):

    if not request.is_ajax():
        return HttpResponseForbidden()

    if request.method != 'POST':
        return json_response({'success': False, 'error': 'wrong method'})
    # Have the hook default value as 'none' if value not found
    # is there a difference between this code and request.user?
    user = request.POST.get('user', None)
    #if not user:
    #    return json_response({'success': False, 'error': 'missing argument'})

    book = request.POST.get('book', None)
    entry = request.POST.get('entry', None)
    # I do not believe you can share an entry without sharing the corresponding book
    if not book and not entry and not user:
        return json_response({'success': False, 'error': 'missing argument'})
    """ Ask the user for an email or username. If user does not exist, validate email anyway
        and return 404. """
    try:
        shared_user = User.objects.get(Q(username=user) | Q(email=user))
    except User.DoesNotExist:
        try:
            validate_email(user)
        except:
            is_email = False
        else:
            is_email = True

        params = {
            'success': False,
            'error': 'user not found',
            'code': 404,
            'is_email': is_email
        }
        return json_response(params)

    if book:
        try:
            shared_book = Book.objects.get(id=int(book))
        except Book.DoesNotExist:
            return json_response({'success': False, 'error': 'book not found'})
        else:
            shared_entry = None
    else:
        try:
            shared_entry = Entry.objects.get(id=int(entry))
        except Entry.DoesNotExist:
            return json_response({
                'success': False,
                'error': 'entry not found'
            })
        else:
            shared_book = None

    if request.user == shared_user:
        return json_response({
            'success': False,
            'error': "You can't share with yourself!"
        })
    # If user did not want to share a book, it must have been an entry.
    #    https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
    if book:
        shared, created = Shared.objects.get_or_create(from_user=request.user,
                                                       to_user=shared_user,
                                                       book=shared_book)
    else:
        shared, created = Shared.objects.get_or_create(from_user=request.user,
                                                       to_user=shared_user,
                                                       entry=shared_entry)
    #If the object didn't have to be created, then user is already sharing either (book/entry) with that person.
    if not created:
        return json_response({
            'success':
            False,
            'error':
            'The book/entry is already shared with %s' %
            shared_user.profile.get_full_name()
        })

    shared.save()

    result = render_to_string('share/share_list_block.html', {'share': shared})
    data = {'success': True, 'result': result}

    return json_response(data)
Пример #45
0
def set_device_resolution(request, id):
    models.VideoDevice.objects.filter(id=id).update(resolution=request.POST['resolution'])
    return json_response("Ok")
Пример #46
0
        return json_response({
            'success': False,
            'error': 'missing argument'
        },
                             error=True)

    message = render_to_string('share/share_invitation.html',
                               {'user_from': user_from})
    try:
        send_mail('You are invited to use Nenjah',
                  message,
                  settings.EMAIL_FROM, [mail_to],
                  fail_silently=True)
    except Exception, error:
        logging.exception("not able to send invitation")
        return json_response({'success': False, 'error': error}, error=True)

    return json_response({'success': True})


@login_required
def sharing(request):
    shared_by_me = Shared.objects.filter(from_user=request.user).order_by(
        'book', 'entry')
    shared_with_me = Shared.objects.filter(to_user=request.user)

    return render(request, 'share/sharing.html', {
        'shared_by_me': shared_by_me,
        'shared_with_me': shared_with_me
    })
Пример #47
0
def json_error(error):
    return json_response({'error': error})
Пример #48
0
def delete(request, id):
    url = settings.VLC_HTTP + '/requests/status.xml'
    params = {'command': 'pl_delete', 'id': id}
    _get_xml(url, params)
    return json_response('Ok')
Пример #49
0
def in_play(request):
    url = settings.VLC_HTTP + '/requests/status.xml'
    input_path = request.POST['input']
    params = {'command': 'in_play', 'input': input_path}
    _get_xml(url, params)
    return json_response('Ok')
Пример #50
0
def halt(request):
    if 'halt' in request.POST:
        models.Command.objects.create(command=models.Command.SYSTEM_DOWN)
        return json_response("Ok")
Пример #51
0
def stop_capture(request):
    if 'stop' in request.POST:
        models.Status.SetValue(models.Status.VIDEO_STARTED, '0')
        return json_response("Stopped")
Пример #52
0
def seek(request):
    url = settings.VLC_HTTP + '/requests/status.xml'
    value = request.POST['value']
    params = {'command': 'seek', 'val': value}
    _get_xml(url, params)
    return json_response('Ok')
Пример #53
0
def repeat(request):
    url = settings.VLC_HTTP + '/requests/status.xml'
    params = {'command': 'pl_repeat'}
    _get_xml(url, params)
    return json_response('Ok')
Пример #54
0
def stop_capture(request):
    if 'stop' in request.POST:
        models.Status.SetValue(models.Status.OBD_STARTED, '0')
        return json_response("Stopped")
Пример #55
0
def start_capture(request):
    if 'start' in request.POST:
        models.Status.SetValue(models.Status.OBD_STARTED, '1')
        return json_response("Started")
Пример #56
0
def start_capture(request):
    if 'start' in request.POST:
        models.Status.SetValue(models.Status.VIDEO_STARTED, '1')
        return json_response("Started")
Пример #57
0
def play(request):
    url = settings.VLC_HTTP + '/requests/status.xml'
    id = request.POST['id']
    params = {'command': 'pl_play', 'id': id}
    _get_xml(url, params)
    return json_response('Ok')