Esempio n. 1
0
def like(feed_id):
    if Feed.objects(id=feed_id,
                    like__nin=[current_user.to_dbref()]).first() is not None:
        Feed.objects(id=feed_id).update_one(push__like=current_user.to_dbref())
    else:
        Feed.objects(id=feed_id).update_one(pull__like=current_user.to_dbref())
    return jsonify(id=str(feed_id))
Esempio n. 2
0
 def delete_api_key(key):
     api_key = database.ApiKey.objects(key=key).first()
     print not api_key
     print api_key.user == current_user.to_dbref()
     if api_key and api_key.user.to_dbref() == current_user.to_dbref():
         api_key.delete()
     else:
         abort(403)
     return redirect(url_for('settings'))
Esempio n. 3
0
def like(oid):
    if current_user.is_anonymous:
        user = User.objects(card_id="00000001").first()
        Evaluation.objects(id=oid).update_one(push__like=user.to_dbref())
    elif Evaluation.objects(id=oid, like__nin=[current_user.to_dbref()
                                               ]).first() is not None:
        Evaluation.objects(id=oid).update_one(
            push__like=current_user.to_dbref())
    else:
        Evaluation.objects(id=oid).update_one(
            pull__like=current_user.to_dbref())
    return jsonify(id=str(oid))
Esempio n. 4
0
 def _save_create(self, doc, force_insert, write_concern):
     if 'owner' in self._fields:
         doc['owner'] = current_user.to_dbref()
     if 'created' in self._fields:
         doc['created'] = datetime.now()
     return super(Document, self)._save_create(doc, force_insert,
                                               write_concern)
Esempio n. 5
0
def data(fid):
    formlinks = FormLink.objects(creator=current_user.to_dbref())
    formlink = FormLink.objects(fid=fid).first()
    # print 'formlink:', formlink
    threads = Thread.objects(formlink=formlink)
    return render_template('forms/dashboard.html', fid=fid,
                           threads=threads, formlinks=formlinks)
Esempio n. 6
0
def like(oid):
    course = Course.objects(id=oid).get_or_404()
    if current_user.is_anonymous:
        user = User.objects(card_id="00000001").first()
        Course.objects(id=oid).update_one(push__like=user.to_dbref())
        course.heat += 1
    elif Course.objects(id=oid, like__nin=[current_user.to_dbref()
                                           ]).first() is not None:
        Course.objects(id=oid).update_one(push__like=current_user.to_dbref())
        course.heat += 1
    else:
        course.heat -= 1
        Course.objects(id=oid).update_one(pull__like=current_user.to_dbref())
    course.save()
    course.reload()
    return jsonify(course)
Esempio n. 7
0
 def my():
     if not current_user.is_authenticated():
         abort(403)
     pastes = database.Paste.objects(user=current_user.to_dbref()).order_by('-expire', '-time')
     if pastes.count() == 0:
         pastes = None
     return render_template("my_pastes.html", pastes=pastes, title="My Pastes")
Esempio n. 8
0
def _post_write(project_id):

    project = Project.objects.get_or_404(id=project_id)
    form = BoardForm(request.form)

    if request.method == 'POST' and form.validate():

        post = ProjectPost()
        post.project = project
        post.writer = current_user.to_dbref()

        form.populate_obj(post)

        # filename = form.tmp_file.name
        # filedata = request.files[filename]
        # if filedata.filename:
        #     post.file = filedata
        #     post.filename = filedata.filename  # todo: python3compatible

        post.save()
        return redirect(url_for(
            '._post_view',
            post_id=post.id))

    return render_template(
        'project/community_write.htm.j2',
        action_url=url_for('board._post_write', project_id=project_id),
        project=project, form=form)
Esempio n. 9
0
    def get(self):
        task_id = request.args.get('id')
        try:
            task = Task.objects.get(id=task_id)
        except ValidationError:
            return render_json({'type': 'error', 'message': u'Неверный таск'})
        if task in current_user.solved_tasks:
            return render_json({'type': 'error', 'message': u'Невозможно начать уже решенный таск'})
        if task in current_user.closed_tasks:
            return render_json({'type': 'error', 'message': u'Невозможно начать проваленный таск'})
        if task.solver:
            return render_json({'type': 'error', 'message': u'Таск уже решают'})
        if task.owner:
            cost = task.cost
        else:
            cost = task.base_cost
        if current_user.get_money() < cost:
            return render_json({'type': 'error', 'message': u'Денег нет?'})
        if len(Task.objects(solver=current_user.id)):
            return render_json({'type': 'error', 'message': u'Вы уже решаете таск, сначала завершите его.'})

        current_user.money -= cost
        current_user.task_started_at = datetime.datetime.now()
        current_user.save()
        print 'open task:', current_user.task_started_at, datetime.datetime.now()
        task.solver = current_user.to_dbref()
        task.save()

        return render_json({'type': 'success', 'message': u'Вы начали таск {}. Вы должны решить его за {} сек.'.format(task.name, task.base_time)})
Esempio n. 10
0
 def get(self):
     try:
         task = Task.objects.get(solver=current_user)
     except DoesNotExist:
         return render_json({'type': 'error', 'message': u'Для остановки времени нужно решать таск.'})
     try:
         duration = abs(int(request.args.get('duration', None)))
     except ValueError:
         return render_json({'type': 'error', 'message': u'Неверное время заморозки'})
     cost = duration * 10 / 60  # calculate cost from freeze duration
     if current_user.get_money() < cost:
         return render_json({'type': 'error', 'message': u'Недстаточно денег!'})
     else:
         if task.expired():
             return render_json({'type': 'error', 'message': u'Таск уже просрочен!'})
         freeze = Freeze.current(task)
         if freeze:
             # if we have mo then one added freeze in future append to end
             freezes = Freeze.objects(created_at__gt=freeze.created_at).order_by('-created_at')
             if len(freezes):
                 freeze = freezes[0]
             created = freeze.created_at + datetime.timedelta(seconds=freeze.duration)
         else:
             created = datetime.datetime.now()
         current_user.money -= cost
         current_user.save()
         freeze = Freeze(created_at=created, user=current_user.to_dbref(), task=task, duration=duration)
         freeze.save()
         return render_json({'type': 'success', 'message': u'Время таска заморожено!'})
Esempio n. 11
0
def accept_invitation_endpoint(project_id: str):
    """
    Accept invitation to the project
    ---
    post:
        summary: Project invitation endpoint.
        description: Accept an invitation to the project.
        responses:
            400:
                description: Parameters are not correct
            200:
                description: User was added to the project
    """
    try:
        if not project_id:
            return make_response(
                jsonify({MESSAGE_KEY: 'Not enough data provided'}),
                HTTPStatus.BAD_REQUEST)

        result = accept_invitation(project_id=project_id,
                                   user=current_user.to_dbref())
        if not result:
            return make_response(jsonify({MESSAGE_KEY: 'Failed to accept'}),
                                 HTTPStatus.INTERNAL_SERVER_ERROR)

        return make_response(jsonify({MESSAGE_KEY: 'Success'}), HTTPStatus.OK)
    except Exception as e:
        logger.exception(f'Failed to register user. Error {e}')
        return make_response(jsonify({MESSAGE_KEY: 'Something bad happened'}),
                             HTTPStatus.INTERNAL_SERVER_ERROR)
Esempio n. 12
0
 def delete(id):
     paste = database.Paste.objects(name=id).first()
     if not paste:
         abort(404)
     if paste.user.to_dbref() != current_user.to_dbref():
         abort(403)
     paste.delete()
     return redirect('/my')
Esempio n. 13
0
def create_form():
    form = CreatFormLink()
    if request.method == 'POST' and form.validate():
        formlink = FormLink(name=form.name.data,
                            creator=current_user.to_dbref())
        formlink.save()
        return redirect('/data')
    return redirect('/data')
Esempio n. 14
0
def payplug_cancel(order_number):
    from ..shop.models.order import Order
    order = Order.objects.get_or_404(number=order_number,
                                     customer=current_user.to_dbref())
    order.payment_data = None
    order.save()
    return redirect(os.path.join(request.url_root, 'orders',
                                 unicode(order_number)))
Esempio n. 15
0
def create():
    form = PostForm(request.form)
    if request.method == 'POST':
        user = current_user.to_dbref()
        Post(title=form.title.data, body=form.body.data, author=user).save()
        return redirect(url_for('blog.index'))

    return render_template('blog/create.html')
Esempio n. 16
0
def payplug_return(order_number):
    from ..shop.models.order import Order
    order = Order.objects.get_or_404(number=order_number,
                                     customer=current_user.to_dbref())
    if order.status == 'awaiting_payment' and order.payment_data:
        order.set_status('awaiting_provider')
        order.save()
    return redirect(os.path.join(request.url_root, 'orders',
                                 unicode(order_number)))
Esempio n. 17
0
 def post(self):
     args = request.get_json()
     post = TYPE_DICT[args['post']].objects(id=args['id']).first()
     comment = Comment(user=current_user.to_dbref(),
                       post=post,
                       content=args['content'])
     comment.save()
     post.comments.append(comment)
     post.save()
     return jsonify({'id': str(comment.id)})
Esempio n. 18
0
 def make_cart(self, data):
     cart = DbCart()
     cart.user = current_user.to_dbref()
     cart.name = data['name']
     lines, errors = CartlineSchema().load(data['lines'], many=True)
     if errors:
         abort(400, {'type': 'fields', 'errors': errors})
     cart.lines = lines
     cart.save()
     return cart
Esempio n. 19
0
 def get(self, number):
     if current_user.is_admin:
         order = Order.objects.get_or_404(number=number)
     else:
         order = Order.objects.get_or_404(
                     customer=current_user.to_dbref(),
                     number=number
                     )
     payment_data = order.trigger_payment()
     return PaymentInfoSchema().dump(payment_data).data
Esempio n. 20
0
 def get(self, number):
     if current_user.is_admin:
         order = Order.objects.get_or_404(number=number)
     else:
         order = Order.objects.get_or_404(
                     customer=current_user.to_dbref(),
                     number=number
                     )
     order.set_status('cancelled')
     return OrderSchema().dump(order).data
Esempio n. 21
0
 def delete(self, id):
     user = User.objects(id=id).first()
     if user is None:
         status_fields = generate_status_fields(NOTFOUND)
         return status_fields, 404
     if user in current_user.following:
         User.objects(id=current_user.id) \
             .update_one(pull__following=user.to_dbref())
         User.objects(id=id) \
             .update_one(pull__follower=current_user.to_dbref())
     return '', 204
Esempio n. 22
0
def invite(project_id: str):
    """
    Invite a user to the project
    ---
    post:
        summary: Project invitation endpoint.
        description: Invite a user or add a manager to the project.
        parameters:
            -   name: project_id
                in: path
                required: true
                type: integer
                description: a project id
            -   in: formData
                name: user_email
                description: a email of user to be invited
                required: true
                type: string
            -   in: formData
                name: manager
                description: True if adding a manager role
                required: false
                type: boolean
        responses:
            400:
                description: Parameters are not correct
            200:
                description: User was invited
    """
    try:
        data = flask.request.json if flask.request.json else flask.request.form
        user_email: str = data.get(USER_EMAIL_KEY)
        manager: bool = True if data.get(MANAGER_KEY,
                                         'False') == 'True' else False

        if not (project_id and user_email):
            return make_response(
                jsonify({MESSAGE_KEY: 'Not enough data provided'}),
                HTTPStatus.BAD_REQUEST)

        result = invite_user(project_id=project_id,
                             user_email=user_email,
                             invitor=current_user.to_dbref(),
                             manager=manager)
        if not result:
            return make_response(
                jsonify({MESSAGE_KEY: 'Failed to send the invitation'}),
                HTTPStatus.INTERNAL_SERVER_ERROR)

        return make_response(jsonify({MESSAGE_KEY: 'Success'}), HTTPStatus.OK)
    except Exception as e:
        logger.exception(f'Failed to register user. Error {e}')
        return make_response(jsonify({MESSAGE_KEY: 'Something bad happened'}),
                             HTTPStatus.INTERNAL_SERVER_ERROR)
Esempio n. 23
0
    def main():
        if current_user.is_authenticated():
            form = PasteForm(request.form)
        else:
            print 'test'
            form = PasteFormNoAuth(request.form)

        if form.validate_on_submit():

            times = {
                '0':None,
                '1':{'minutes':+15},
                '2':{'minutes':+30},
                '3':{'hours':+1},
                '4':{'hours':+6},
                '5':{'hours':+12},
                '6':{'days':+1},
                '7':{'weeks':+1},
                '8':{'months':+1}
            }
            paste = database.Paste()

            paste.paste = form.text.data
            paste.digest = sha1(paste.paste.encode('utf-8')).hexdigest()

            if (current_user.is_authenticated()):
                paste.user = current_user.to_dbref()
            #Create a name and make sure it doesn't exist
            paste.name = random_string()
            collision_check = database.Paste.objects(name__exact=paste.name).first()
            while collision_check is not None:
                paste.name = random_string()
                collision_check = database.Paste.objects(name__exact=paste.name).first()

            if form.language.data is not None:
                paste.language = form.language.data
            else:
                try:
                    paste.language = guess_lexer(form.text.data).name
                except:
                    paste.language = 'text'
            paste.time = datetime.utcnow()

            if times.get(form.expiration.data) is not None:
                paste.expire = arrow.utcnow().replace(**times.get(form.expiration.data)).datetime
            if times.get(form.expiration.data) is None and not current_user.is_authenticated():
                paste.expire = arrow.utcnow.replace(**times.get(7))

            paste.save()
            return redirect('/{id}'.format(id=paste.name))


        return render_template('new_paste.html', form=form)
Esempio n. 24
0
def data_view(fid, tid):
    formlinks = FormLink.objects(creator=current_user.to_dbref())
    formlink = FormLink.objects(fid=fid).first()
    # print 'formlink:', formlink
    threads = Thread.objects(formlink=formlink)
    thread = Thread.objects(tid=tid).first()
    datas = FormData.objects(thread=thread).order_by('id')
    main = FormData.objects(thread=thread).order_by('id').first()
    # for x in mains:
    #     print 'hhhhhh', x.load
    # main =  None
    return render_template('forms/dashboard.html', fid=fid, datas=datas,
                           threads=threads, formlinks=formlinks, tid=tid, main=main)
Esempio n. 25
0
 def put(self, id):
     user = User.objects(id=id).first()
     if user is None:
         status_fields = generate_status_fields(NOTFOUND)
         return status_fields, 404
     if user not in current_user.following:
         User.objects(id=current_user.id) \
             .update_one(push__following=user.to_dbref())
         User.objects(id=id) \
             .update_one(push__follower=current_user.to_dbref())
         status_fields = generate_status_fields(OK)
     else:
         status_fields = generate_status_fields(EXISTING)
     return status_fields, 202
Esempio n. 26
0
 def get(self, number):
     if current_user.is_admin:
         return OrderSchemaForAdmin().dump(
                     Order.objects.get_or_404(
                         number=number
                         )
                     ).data
     else:
         return OrderSchema().dump(
                     Order.objects.get_or_404(
                         customer=current_user.to_dbref(),
                         number=number
                         )
                     ).data
Esempio n. 27
0
def pdf_invoice(number):
    if current_user.is_admin:
        order = Order.objects.get_or_404(number=number)
    else:
        order = Order.objects.get_or_404(
                    customer=current_user.to_dbref(),
                    number=number
                    )
    strio = cStringIO.StringIO()
    strio.write(order.get_pdf_invoice())
    strio.seek(0)
    return send_file(strio,
                     attachment_filename='{}.pdf'.format(order.invoice_number),
                     mimetype='application/pdf')
Esempio n. 28
0
 def get(self):
     options = orders_reqparser.parse_args()
     options = dict((k, v) for k, v in options.iteritems() if v is not None)
     if current_user.is_admin:
         schema = OrderSchemaForAdminList
         orders = Order.objects(
                     **options
                     )
     else:
         schema = OrderSchemaForList
         orders = Order.objects(
                     customer=current_user.to_dbref(),
                     **options
                     )
     return schema(many=True).dump(orders).data
Esempio n. 29
0
    def generate(self):
        apiobj = current_app.view_functions[self.endpoint].view_class()

        if hasattr(apiobj, 'queryset_advsearch'):
            d = {}
            d.update(self.endpoint_kwargs)
            d['args'] = self.url_params
            queryset = apiobj.queryset_advsearch(**d)
        else:
            queryset = apiobj.queryset(**self.endpoint_kwargs)

        query = apiobj._build_queryset(
            queryset,
            search=self.url_params.get('search', None),
            fields=self.url_params.get('fields', None),
            filter_=self.url_params.get('filter_', None),
            sorted_=self.url_params.get('sorted_', None),
            order=self.url_params.get('order', 'asc'),
        )
        total_count = query.count()

        fileid = str(current_user.to_dbref().id)
        filename = "{0}.xlsx".format(fileid)
        filepath = os.path.join(current_app.config['EXCEL_UPLOAD_DIR'],
                                filename)
        # current_app.logger.debug(filepath)
        workbook = xlsxwriter.Workbook(filepath, {'constant_memory': True})
        worksheet = workbook.add_worksheet('ERCC')
        for colidx, column in enumerate(self.columns):
            worksheet.write(0, colidx, column.get('title', 'Nonamed'))
        current_app.logger.debug(self.columns[-1])
        for index, row in enumerate(
                apiobj._yield(query,
                              limit=0,
                              fields=self.url_params.get('fields', None))):
            for colidx, column in enumerate(self.columns):
                try:
                    val = _dot_getter(row, column.get('field'))
                except (ValueError, AttributeError):
                    val = '-'
                else:
                    current_app.logger.debug(val)
                    worksheet.write(index + 1, colidx, val)
            yield f'data: {index+1}/{total_count}\n\n'
        workbook.close()
        url = url_for('portal.download_file', file_id=fileid)
        yield f'event: completed\ndata: <a href="{url}">엑셀파일을 다운로드받으세요.</a>\n\n'
Esempio n. 30
0
def new_project():
    """
    Create a new project
    ---
    post:
        summary: Project creation endpoint.
        description: Create a new project with user issuing request being a manager.
        parameters:
            -   in: formData
                name: name
                description: a name of the project
                required: true
                type: string
        responses:
            400:
                description: Parameters are not correct
            201:
                description: Project was created
    """
    try:
        data = flask.request.json if flask.request.json else flask.request.form
        name: str = data.get(NAME_KEY)

        if not name:
            return make_response(
                jsonify({MESSAGE_KEY: 'Not enough data provided'}),
                HTTPStatus.BAD_REQUEST)

        project = create_new_project(name, current_user.to_dbref())
        if not project:
            return make_response(
                jsonify({MESSAGE_KEY: 'Failed to create project'}),
                HTTPStatus.INTERNAL_SERVER_ERROR)

        return make_response(
            jsonify({
                MESSAGE_KEY: 'Success',
                PROJECT_KEY: project
            }), HTTPStatus.CREATED)
    except Exception as e:
        logger.exception(f'Failed to register user. Error {e}')
        return make_response(jsonify({MESSAGE_KEY: 'Something bad happened'}),
                             HTTPStatus.INTERNAL_SERVER_ERROR)
Esempio n. 31
0
    def get(self):
        try:
            task = Task.objects.get(solver=current_user)
        except DoesNotExist:
            return render_json({'type': 'error', 'message': u'Вы не решаете таск. Хакер шоле?'})
        flag = request.args.get('flag', None)
        if task.expired():
            return render_json({'type': 'error', 'message': u'Вы просрочили таск.'})
        print(task.flag.upper(), flag.upper())
        if task.flag.upper() == flag.upper():
            solve_time = task.solving_time()
            # We have new tsar of mount
            if not task.owner or solve_time < task.best_time:
                current_user.money += (task.base_cost * 2)
                current_user.solved_tasks.append(task)
                current_user.task_started_at = None
                current_user.save()

                if task.owner:
                    prev_leader = User.objects.get(name=task.owner.name)
                    diff = (datetime.datetime.now() - task.last_solved_at)
                    prev_leader.money += (diff.seconds // 60) * task.cost * 0.02

                task.owner = current_user.to_dbref()
                task.best_time = solve_time
                task.last_solved_at = datetime.datetime.now()
                task.solver = None
                task.save()

                return render_json({'type': 'success', 'message': u'Поздравляем, вы решили таск "{}"'.format(task.name)})

            current_user.money += task.base_cost
            current_user.solved_tasks.append(task)
            current_user.task_started_at = None
            current_user.save()

            task.solver = None
            task.save()

            return render_json({'type': 'success', 'message': u'Поздравляем, вы решили таск. Однако очки не зачислились, т.к. вы затратили больше времени, чем предыдущая команда "{}"'.format(task.owner.name)})
        else:
            return render_json({'type': 'error', 'message': u'Неверный флаг'})
Esempio n. 32
0
    def set_status(self, state):
        if state in constants.USER_STATES:
            status = {
                'state'      : state,
                #TODO 09-08-2018 19:04 >> how to save by ObjectId?
                'modered_by' : current_user.to_dbref(),
                'date'       : datetime.now(),
                'acked'      : False,
            }

            self.status.append(status)

            if   self.is_silenced():
                self.silenced_times  += 1
            elif self.is_suspended():
                self.suspended_times += 1

        self.save()

        return self
Esempio n. 33
0
def _qna_write(slug):

    pg = ProjectGroup.objects.get_or_404(slug=slug)
    form = BoardForm(request.form)

    if request.method == 'POST' and form.validate():
        post = ProjectGroupQnA()
        post.project_group = pg
        post.writer = current_user.to_dbref()

        form.populate_obj(post)
        post.save()
        return redirect(url_for(
            '._qna_view',
            post_id=post.id))

    return render_template(
        'board/_post_write.htm.j2',
        action_url=url_for('board._qna_write', slug=slug),
        form=form
    )
Esempio n. 34
0
 def get(self):
     return CartSchema(many=True).dump(DbCart.objects(
                                             user=current_user.to_dbref()
                                             )).data
Esempio n. 35
0
 def get(self, cart_id):
     return CartSchema().dump(DbCart.objects.get_or_404(
                                             user=current_user.to_dbref(),
                                             id=cart_id
                                             )).data
Esempio n. 36
0
def dashboard():
    formlinks = None
    if current_user.is_authenticated:
        formlinks = FormLink.objects(creator=current_user.to_dbref())

    return render_template('forms/dashboard.html', formlinks=formlinks)
Esempio n. 37
0
 def delete(self, cart_id):
     DbCart.objects.get_or_404(
                         user=current_user.to_dbref(),
                         id=cart_id
                         ).delete()
     return {'status': 'OK'}
Esempio n. 38
0
def project_activities(project_id: str):
    """
    Find project activities
    ---
    get:
        summary: Find activities.
        description: Find activities in specified project.
        parameters:
            -   name: project_id
                in: path
                required: true
                type: integer
                description: a project id
            -   name: offset
                in: query
                required: true
                type: integer
                description: a number of activities to skip
            -   name: amount_to_return
                in: query
                required: true
                type: integer
                description: amount of activities to return, max is 10000
            -   name: filters
                in: query
                required: false
                type: string
                description: filters for activity, example {"activity_type"&#58; "os"}
            -   name: start_time
                in: query
                required: false
                type: string
                description: minimum start time of an activity
            -   name: end_time
                in: query
                required: false
                type: string
                description: maximum end time of an activity
        responses:
            404:
                description: Activities were not found
            400:
                description: Wrong format
            200:
                description: A list of activities was returned
    """
    data = flask.request.args
    offset: int = int(data.get(OFFSET_KEY, 0))
    amount_to_return: int = min(int(data.get(AMOUNT_TO_RETURN_KEY, 100)),
                                10000)
    filters = data.get(FILTERS_KEY, {})
    start_time = data.get(START_TIME_KEY, None)
    end_time = data.get(END_TIME_KEY, None)

    if not isinstance(filters, dict):
        try:
            filters = json.loads(filters)
        except Exception:
            return make_response(jsonify({MESSAGE_KEY: 'Wrong format'}),
                                 HTTPStatus.BAD_REQUEST)

    activities = get_project_activities(project_id=project_id,
                                        user=current_user.to_dbref(),
                                        offset=offset,
                                        items_to_return=amount_to_return,
                                        filters=filters,
                                        start_time=start_time,
                                        end_time=end_time)
    if activities is None:
        return make_response(
            jsonify({MESSAGE_KEY: 'Failed to fetch activities'}),
            HTTPStatus.INTERNAL_SERVER_ERROR)
    if activities == -1:
        return make_response(
            jsonify({MESSAGE_KEY: 'Wrong format for filters'}),
            HTTPStatus.BAD_REQUEST)

    if not activities:
        return make_response(
            jsonify({MESSAGE_KEY:
                     'Activities of current user were not found'}),
            HTTPStatus.NOT_FOUND)
    activities_list = [{k: str(v)
                        for k, v in activity.to_mongo().items()}
                       for activity in activities]

    return make_response(
        jsonify({
            MESSAGE_KEY: 'Success',
            ACTIVITIES_KEY: activities_list
        }), HTTPStatus.OK)
Esempio n. 39
0
    def make_order(self, data):
        """
        Execute it only when creating an order.

        An order must never be modified as a whole.
        """
        # TODO Error management would be needed here
        # (missing objects especially)
        order = Order()
        order.customer = current_user.to_dbref()
        order.currency = app.config['CURRENCY']
        delivery_address = Address.objects.get(id=data['delivery_address'])
        order.set_delivery(delivery_address)
        billing_address_id = data.get('billing_address', None)
        delivery_as_billing = data.get('delivery_as_billing', False)
        if not delivery_as_billing and billing_address_id:
            billing_address = Address.objects.get(id=billing_address_id)
        else:
            billing_address = delivery_address
        order.set_billing(billing_address)
        products = []
        subtotal = Price(0)
        total_weight = 0
        global_delay = 0
        for productdata in data.get('cart', []):
            this_data_s = productdata.get('data')
            if this_data_s and this_data_s != '{}':
                this_data = dict(i.split(':') for i in this_data_s.split(','))
            else:
                this_data = {}
            productobj = BaseProduct.objects.get(
                                id=productdata['product']['id']
                                )
            product = OrderProduct(
                reference=productdata['product']['reference'],
                product=productobj,
                name=productobj.name.get(get_locale(), u''),
                data=this_data
                )
            product.set_quantity(productdata['quantity'])
            global_delay = max(global_delay, product.delay)
            price = productobj.get_price_per_item(this_data)
            product.set_gross_price(price.gross)
            product.set_net_price(price.net)
            line_price = price * product.quantity
            product.set_line_gross_price(line_price.gross)
            product.set_line_net_price(line_price.net)
            subtotal += line_price
            total_weight += (
                productobj.get_weight(this_data) * product.quantity
                )
            products.append(product)
        order.products = products
        order.set_subtotal(subtotal)
        carrierobj = Carrier.objects.get(id=data['carrier'])
        order.carrier = carrierobj
        order.carrier_description = carrierobj.full_description
        shipping_price = delivery_address.country.get_shipping_price(
                                                        carrierobj,
                                                        total_weight
                                                        )
        order.set_shipping(shipping_price)
        order.set_total(subtotal+shipping_price)
        order.set_payment_mode(data.get('payment'))
        order.accept_reused_package = data.get('accept_reused_package', False)
        order.paper_invoice = data.get('paper_invoice', False)
        order.delay = global_delay
        order.save()
        current_user.latest_delivery_address = unicode(delivery_address.id)
        current_user.latest_billing_address = unicode(billing_address.id)
        current_user.latest_delivery_as_billing = delivery_as_billing
        current_user.latest_carrier = unicode(carrierobj.id)
        current_user.latest_payment = order.payment_id
        current_user.latest_reused_package = order.accept_reused_package
        current_user.save()
        return order
Esempio n. 40
0
def activity_add():
    """
    Add an activity
    ---
    post:
        summary: Add an activity.
        description: Add an activity or multiple activities to the current user.
        parameters:
            -   name: activity
                in: formData
                required: true
                description: json containing all specified parameters
                type: string
            -   name: activities
                in: formData
                required: false
                description: List containing activity_data
                type: array
                items:
                    type: string
            -   name: start_time
                in: formData
                required: true
                type: string
                description: a start time of the activity
            -   name: end_time
                in: formData
                required: true
                type: string
                description: an end time of the activity
            -   name: executable_name
                in: formData
                required: true
                type: string
                description: a name of the current executable
            -   name: browser_url
                in: formData
                required: false
                type: string
                description: a url opened during the activity
            -   name: browser_title
                in: formData
                required: false
                type: string
                description: a title of the browsing window
            -   name: ip_address
                in: formData
                required: true
                type: string
                description: an ip address of the user
            -   name: mac_address
                in: formData
                required: true
                type: string
                description: an mac address of the user
            -   name: idle_activity
                in: formData
                required: false
                type: boolean
                description: if activity is an idle one
            -   name: activity_type
                in: formData
                required: false
                type: string
                description: a type of activity collected (os, eclipse tab and etc)
        responses:
            400:
                description: Parameters are not correct
            201:
                description: Activity was added
    """
    data = flask.request.json if flask.request.json else flask.request.form
    activity_data = data.get(ACTIVITY_KEY)
    if not isinstance(activity_data, dict):
        try:
            activity_data = json.loads(activity_data)
        except Exception:
            return make_response(jsonify({MESSAGE_KEY: 'Wrong format'}),
                                 HTTPStatus.BAD_REQUEST)

    if ACTIVITIES_KEY in activity_data:
        #  Add multiple activities
        activities = [(activity, current_user.to_dbref())
                      for activity in activity_data.get(ACTIVITIES_KEY, [])]
        all_result = execute_function_in_parallel(add_activity, activities)
        result = 1
        for part_result in all_result:
            if not part_result:
                result = part_result
        if result:
            result = all_result
        else:
            # Delete those activities that were added
            for part_result in all_result:
                if part_result:
                    delete_activity(part_result)
    else:
        result = add_activity(activity_data, current_user.to_dbref())

    if not result:
        return make_response(
            jsonify({MESSAGE_KEY: 'Failed to create activity'}),
            HTTPStatus.INTERNAL_SERVER_ERROR)

    return make_response(
        jsonify({
            MESSAGE_KEY: 'Success',
            ACTIVITY_ID_KEY: result
        }), HTTPStatus.CREATED)
Esempio n. 41
0
 def settings():
     keys = database.ApiKey.objects(user=current_user.to_dbref())
     return render_template('settings.html', keys=keys)
Esempio n. 42
0
 def new_api_key():
     key = random_string(size=32)
     api_key = database.ApiKey(user=current_user.to_dbref(), key=key)
     api_key.save()
     return redirect(url_for('settings'))