Example #1
0
def post_video():
    request_body = request.get_json()
    if "title" in request_body and "release_date" in request_body and "total_inventory" in request_body:
        video = Video(**request_body)
        video.available_inventory = video.total_inventory
        db.session.add(video)
        db.session.commit()
        return jsonify(video.video_info()), 201
    return jsonify({"details": "Invalid data"}), 400
Example #2
0
def add_video():
    form = VideoAddForm()
    # 每次刷新列表,动态加载最新的标签
    # form.tag_id.choices = [(v.id, v.name) for v in Tag.query.all()]
    form.validate_for_api()
    with db.auto_commit():
        video = Video()
        video.name = form.name.data
        try:
            file = request.files[form.url.name]
            if not allowed_video_file(file.filename):
                return ReturnObj.get_response(
                    ReturnEnum.VIDEO_TYPE_ERROR.value,
                    "只允许上传mp4 avi flv wmv格式")
            file_url = secure_filename(file.filename)
            url = change_filename(file_url)
            file.save(os.path.join(current_app.config["VIDEO_DIR"], url))
            try:
                video_clip = VideoFileClip(
                    os.path.join(current_app.config["VIDEO_DIR"], url))
                video.length = video_clip.duration
                video_clip.reader.close()
                video_clip.audio.reader.close_proc()
            except Exception as e:
                print(e)
                video.length = None
            video.url = urljoin(current_app.config["VIDEO_PATH"], url)
        except Exception as e:
            return ReturnObj.get_response(ReturnEnum.UPLOAD_VIDEO.value,
                                          "请上传视频")
        try:
            file = request.files[form.logo.name]
            if not allowed_image_file(file.filename):
                return ReturnObj.get_response(
                    ReturnEnum.IMAGE_TYPE_ERROR.value,
                    "只允许上传png jpg jpeg gif格式")
            file_logo = secure_filename(file.filename)
            logo = change_filename(file_logo)
            file.save(os.path.join(current_app.config["LOGO_DIR"], logo))
            video.logo = urljoin(current_app.config["LOGO_PATH"], logo)
        except Exception as e:
            return ReturnObj.get_response(ReturnEnum.UPLOAD_VIDEO_LOGO.value,
                                          "请上传视频封面")
        # 默认所属用户为pilipili番剧
        video.user_id = 6666
        video.info = form.info.data
        # 默认所属标签为连载动画
        video.tag_id = 18
        db.session.add(video)
    write_oplog()
    return ReturnObj.get_response(ReturnEnum.SUCCESS.value, "success")
Example #3
0
def get_video(video_id):
    video = Video.get_one(video_id)
    project = video_service.get_video_project(video_id)
    res = video.to_dict()
    res['file_size'] = round(res['file_size'] / 1024 / 1024, 2)
    res['projects'] = project
    return api_success(res)
Example #4
0
def post_feed():
    """
    Insert feed
    """
    data = request.get_json(silent=True)
    type = data['type']
    if type == 1:
        video = data['video']
        title = video['title']
        description = video['description']
        url = video['url']
        v_result = Video.create(title=title, description=description, url=url)

    if type == 2:
        photo = data['photo']
        title = photo['title']
        description = photo['description']
        url = photo['url']
        Photo.create(title=title, description=description, url=url)

    if type == 3:
        article = data['news']

    print(data)

    if 'name' in data and 'description' in data and 'slug' in data:
        name = data['name']
        description = data['description']
        slug = data['slug']
        Feed.create(name=name, description=description, slug=slug)
        return make_response(jsonify({'success': True, 'result': 'Category Created'}), 201)
    else:
        return make_response(jsonify({'success': False, 'result': 'Incomplete parameters'}), 400)
Example #5
0
    def check_out(cls, video_id, customer_id):
        new_rental = cls(video_id=video_id, customer_id=customer_id)
        if not new_rental:
            return None

        video = Video.get_video_by_id(new_rental.video_id)
        customer = Customer.get_customer_by_id(new_rental.customer_id)

        # If no available inventory, you can't rent the video
        if video.available_inventory <= 0:
            return None

        new_rental.save()
        video.available_inventory -= 1
        customer.videos_checked_out_count += 1
        video.save()
        customer.save()

        videos_checked_out_count = customer.videos_checked_out_count
        available_inventory = video.available_inventory

        return {
            # "id": new_rental.id,
            "video_id": new_rental.video_id,
            "customer_id": new_rental.customer_id,
            "videos_checked_out_count": videos_checked_out_count,
            "available_inventory": available_inventory,
            "due_date": new_rental.due_date
        }
Example #6
0
def edit_uploadvideo():
    """编辑审核状态"""
    form = VerificationForm().validate_for_api()
    verification = form.verification
    try:
        verification.status = form.status.data
        verification.admin_id = current_user.id
        db.session.add(verification)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
    uploadvideo = form.uploadvideo
    if verification.status == 1:
        # 审核通过
        try:
            # 审核通过,添加到视频表
            video = Video()
            video.user_id = uploadvideo.user_id
            video.tag_id = uploadvideo.tag_id
            video.name = uploadvideo.name
            video.info = uploadvideo.info

            # 更换视频封面文件位置
            file_name = uploadvideo.logo.rsplit("/", 1)[1]
            src = os.path.join(current_app.config["TMP_DIR"], file_name)
            if os.path.isfile(src):
                des = os.path.join(current_app.config["LOGO_DIR"], file_name)
                shutil.move(src, des)
            else:
                return ReturnObj.get_response(
                    ReturnEnum.UPLOAD_VIDEO_LOGO.value, "上传视频封面不存在")
            video.logo = uploadvideo.logo.replace("tmp", "logo")

            # 更换视频文件位置
            file_name = uploadvideo.url.rsplit("/", 1)[1]
            src = os.path.join(current_app.config["TMP_DIR"], file_name)
            if os.path.isfile(src):
                des = os.path.join(current_app.config["VIDEO_DIR"], file_name)
                shutil.move(src, des)
            else:
                return ReturnObj.get_response(
                    ReturnEnum.UPLOADVIDE0_NOT_EXIST.value, "上传视频不存在")
            video.url = uploadvideo.url.replace("tmp", "video")

            video.release_time = datetime.now()
            db.session.add(video)
        except Exception as e:
            print(e)
            db.session.rollback()
    write_oplog()
    return ReturnObj.get_response(ReturnEnum.SUCCESS.value, "success")
Example #7
0
def video_save():
    data = request.get_json()
    v = Video(path='/home/pi/Desktop/remoteRobotVideos',
              name=data['videoname'] + '.mp4',
              preview_frame=data['videoname'] + '.jpg')
    db.session.add(v)
    db.session.commit()
    return Response(status=200)
Example #8
0
def batch_add_videos(datas):
    for data in datas:
        data['file_type'] = os.path.splitext(data['file_path'])[1].strip('.')
        data['file_size'] = get_size(data['file_path'])
        video = Video.create(data)
        res = video.to_dict()
        project_ids = data.get('project_ids', [])
        generate_project(res['id'], project_ids)
Example #9
0
 def to_json(self):
     video = Video.get_video_by_id(self.video_id)
     return {
         "title": video.title,
         "due_date": self.due_date,
         "release_date": video.release_date,
         #"checkout_date": (self.due_date - timedelta(days=7))
     }
 def create(cls, data):
     errors = cls.validate_data(data)
     if errors:
         return make_response(errors, 400)
     new_video = Video(title = data["title"], release_date = data["release_date"], inventory = data["total_inventory"])
     db.session.add(new_video)
     db.session.commit()
     json = cls.video_json(new_video)
     return make_response(json, 201)
Example #11
0
def add_video():
    """添加番剧视频"""
    form = BangumiAddVideoForm().validate_for_api()
    bangumi = form.obj
    with db.auto_commit():
        video = Video()
        video.name = form.name.data
        try:
            file = request.files[form.url.name]
            if not allowed_video_file(file.filename):
                return ReturnObj.get_response(
                    ReturnEnum.VIDEO_TYPE_ERROR.value,
                    "只允许上传mp4 avi flv wmv格式")
            file_url = secure_filename(file.filename)
            url = change_filename(file_url)
            file.save(os.path.join(current_app.config["VIDEO_DIR"], url))
            try:
                video_clip = VideoFileClip(
                    os.path.join(current_app.config["VIDEO_DIR"], url))
                video.length = video_clip.duration
                video_clip.reader.close()
                video_clip.audio.reader.close_proc()
            except Exception as e:
                print(e)
                video.length = None
            video.url = urljoin(current_app.config["VIDEO_PATH"], url)
        except Exception as e:
            return ReturnObj.get_response(ReturnEnum.UPLOAD_VIDEO.value,
                                          "请上传视频")
        try:
            file = request.files[form.logo.name]
            if not allowed_image_file(file.filename):
                return ReturnObj.get_response(
                    ReturnEnum.IMAGE_TYPE_ERROR.value,
                    "只允许上传png jpg jpeg gif格式")
            file_logo = secure_filename(file.filename)
            logo = change_filename(file_logo)
            file.save(os.path.join(current_app.config["LOGO_DIR"], logo))
            video.logo = urljoin(current_app.config["LOGO_PATH"], logo)
        except Exception as e:
            return ReturnObj.get_response(ReturnEnum.UPLOAD_VIDEO_LOGO.value,
                                          "请上传视频封面")
        db.session.add(video)
    with db.auto_commit():
        video = Video.query.filter(Video.name == form.name.data).order_by(
            Video.create_time.desc()).first()
        bangumi.episodes += 1
        bangumi.new_piece += 1
        if form.is_finish.data == 1:
            bangumi.is_finish = 1
        db.session.add(bangumi)
    with db.auto_commit():
        episode = Episode()
        episode.video_id = video.id
        episode.bangumi_id = bangumi.id
        episode.piece = bangumi.new_piece
        db.session.add(episode)
    write_oplog()
    return ReturnObj.get_response(ReturnEnum.SUCCESS.value, "success")
Example #12
0
def videos_delete(video_id):
    video = Video.get_video_by_id(video_id)
    if not video:
        return {"message": f"Video {video_id} was not found"}, 404

    video.delete()

    return {
        "id": video.id,
    }, 200
Example #13
0
def videos_create():
    request_body = request.get_json()

    if invalid_video_data(request_body):
        return {"message": "Invalid Request"}, 400

    title = request_body.get("title")
    release_date = request_body.get("release_date")
    total_inventory = request_body.get("total_inventory")
    available_inventory = total_inventory

    video = Video(title=title,
                  release_date=release_date,
                  total_inventory=total_inventory,
                  available_inventory=available_inventory)
    video.save()

    return {
        "id": video.id,
    }, 201
Example #14
0
def add_video():
    data = request.json
    data['file_type'] = os.path.splitext(data['file_path'])[1].strip('.')
    if data['file_type'] not in video_allow_extensions:
        raise ApiError('视频格式不正确')
    data['file_size'] = video_service.get_size(data['file_path'])
    video = Video.create(data)
    res = video.to_dict()
    project_ids = data.get('project_ids', [])
    video_service.generate_project(res['id'], project_ids)
    return api_success(res)
Example #15
0
def videos():
    request_body = request.get_json()
    if "title" not in request_body or "release_date" not in request_body or "total_inventory" not in request_body:
        return make_response({"details": "Invalid data"}, 400)
    else:
        new_video = Video(title=request_body["title"],
                          release_date=request_body["release_date"],
                          total_inventory=request_body["total_inventory"],
                          available_inventory=request_body["total_inventory"])
        db.session.add(new_video)
        db.session.commit()
        return make_response({"id": new_video.id}, 201)
Example #16
0
def videos():
    try:
        request_body = request.get_json()
        new_video = Video(title=request_body["title"],
                          release_date=request_body["release_date"],
                          total_inventory=request_body["total_inventory"])

        db.session.add(new_video)
        db.session.commit()

        return jsonify({"id": new_video.video_id}), 201
    except KeyError:
        return jsonify({"details": "Invalid data"}), 400
Example #17
0
    def post(self, req):
        # 获取信息
        videoName = req.POST.get('videoName')
        image = req.POST.get('image')
        videoType = req.POST.get('videoType')
        videoSource = req.POST.get('videoSource')
        nation = req.POST.get('nation')
        desc = req.POST.get('desc')

        userID = req.session.get(SESSION_NAME)
        exists = User.objects.filter(pk=userID).exists()
        if not exists:
            return redirect('{}?error={}'.format(reverse('external_video'), '用户不存在'))

        user = User.objects.filter(pk=userID)[0]

        # 如果有该填写的区域为空
        if not all([videoName, image, videoType, videoSource, nation, desc]):
            return redirect('{}?error={}'.format(reverse('external_video'), '请确保所有内容均被正确填写'))

        # 如果枚举类型错误
        if not checkEnum([VideoType, VideoSource, Nation], [videoType, videoSource, nation]):
            return redirect('{}?error={}'.format(reverse('external_video'), '种类、国家或视频源选择错误'))

        # 都无问题后存入DB
        video = Video(
            user=user,
            videoName=videoName,
            image=image,
            videoType=videoType,
            source=videoSource,
            nation=nation,
            desc=desc
        )
        video.save()

        return redirect(reverse('external_video'))
Example #18
0
def upload_media(request):
    latest_files = request.files.getlist("files")
    event = request.form.get("event")
    week = request.form.get("week")
    if latest_files is not None:
        for uploaded_file in latest_files:
            original_filename, extension = os.path.splitext(
                uploaded_file.filename)
            MAX_SIZE = 1500, 1500

            # Spara orginalet
            filename = str(
                uuid.uuid4()
            ) + extension  ## Generera ett unikt filnamn så att det inte blir krockar
            path = os.path.join("static", "media", filename)
            img = Img.open(uploaded_file)
            img.thumbnail(MAX_SIZE)

            local_path = os.path.join(os.getcwd(), path)
            img.save(local_path)

            # Skapa en thumbnail
            thumb = Img.open(local_path)
            filename_thumb = str(uuid.uuid4()) + extension

            path_thumb = os.path.join("static", "media", filename_thumb)
            local_path_thumb = os.path.join(os.getcwd(), path_thumb)

            thumb.thumbnail([400, 400])
            thumb.save(local_path_thumb)

            new_img = Image(filename=path,
                            event_id=event,
                            week=week,
                            thumbnail=path_thumb)
            db.session.add(new_img)

    latest_videos = request.form.getlist("videos")
    if latest_videos is not None:
        for video in latest_videos:
            embed_link, thumbnail = handle_video(video)
            new_vid = Video(video_link=embed_link,
                            event_id=event,
                            week=week,
                            thumbnail=thumbnail)
            db.session.add(new_vid)

    db.session.commit()
    return True
Example #19
0
def videos_update(video_id):
    video = Video.get_video_by_id(video_id)
    if not video:
        return {"message": f"Video {video_id} was not found"}, 404

    request_body = request.get_json()
    if invalid_video_data(request_body):
        return {"message": "Invalid data"}, 400

    video.title = request_body.get("title")
    video.release_date = request_body.get("release_date")
    video.total_inventory = request_body.get("total_inventory")

    video.save()

    return video.to_json(), 200
Example #20
0
def create_videos():

    request_body = request.get_json()

    if "title" not in request_body or "release_date" not in request_body or "total_inventory" not in request_body:
        return jsonify({"errors": "Not Found"}), 400

    video = Video(title=request_body["title"],
                  release_date=request_body["release_date"],
                  total_inventory=request_body["total_inventory"],
                  available_inventory=request_body['total_inventory'])

    db.session.add(video)
    db.session.commit()

    return jsonify({"id": video.id}), 201
Example #21
0
def add_video():
    video_to_add = request.get_json()

    validation = video_validation(video_to_add)

    if not validation:
        return err_400()

    new_video = Video(title=video_to_add["title"],
                      release_date=video_to_add["release_date"],
                      total_inventory=video_to_add["total_inventory"],
                      available_inventory=video_to_add["total_inventory"])

    db.session.add(new_video)
    db.session.commit()

    return jsonify({"id": new_video.video_id}), 201
def create_video():
    """Create a video for the database"""
    request_body = request.get_json()

    if "title" not in request_body or "release_date" not in request_body or "total_inventory" not in request_body:
        return make_response(
            {
                "details":
                "Video title, release date and total in inventory must all be provided, and they must be string, datetime and integer values, respectively."
            }, 400)

    new_video = Video(title=request_body["title"],
                      release_date=request_body["release_date"],
                      total_inventory=request_body["total_inventory"],
                      available_inventory=request_body["total_inventory"])

    db.session.add(new_video)
    db.session.commit()
    return make_response({"id": new_video.video_id}, 201)
Example #23
0
def get_rentals_for_video(video_id):
    video = Video.get_video_by_id(video_id)
    if not video:
        return {"message": f"Video {id} not found"}, 404

    rentals = video.rentals

    results = []
    for rental in rentals:
        customer = Customer.query.get_or_404(rental.customer_id)
        if rental.status:
            results.append({
                "due_date": rental.due_date,
                "name": customer.name,
                "phone": customer.phone,
                "postal_code": int(customer.postal_code),
                "status": rental.status
            })

    return jsonify(results), 200
Example #24
0
def check_in_video():
    request_body = request.get_json()

    if invalid_rental_data(request_body):
        return {"message": "Invalid request body"}, 400

    video = Video.get_video_by_id(request_body["video_id"])

    if not video:
        return {"message": f"Video {request_body['video_id']} not found."}, 404

    customer = Customer.get_customer_by_id(request_body['customer_id'])

    if not customer:
        return {
            "message": f"Customer {request_body['customer_id']} not found"
        }, 404

    result = Rental.check_in(video_id=video.id, customer_id=customer.id)

    return result
Example #25
0
    def check_in(cls, customer_id, video_id):
        checked_in_rental = cls.query.filter(
            Rental.customer_id == customer_id).filter(
                Rental.video_id == video_id).filter(
                    Rental.status == "Checked_out").first()

        if not checked_in_rental:
            return {
                "message":
                f"No outstanding rentals for customer # {customer_id} and video {video_id}"
            }, 400

        checked_in_rental.status = None

        video = Video.get_video_by_id(checked_in_rental.video_id)
        customer = Customer.get_customer_by_id(checked_in_rental.customer_id)

        if not video:
            return {"message": f"Movie id: {video_id} not found"}, 404

        if not customer:
            return {"message": f"Customer id: {customer_id} not found"}, 404

        video.available_inventory += 1
        customer.videos_checked_out_count -= 1

        checked_in_rental.save()
        video.save()
        customer.save()

        videos_checked_out_count = customer.videos_checked_out_count
        available_inventory = video.available_inventory

        return {
            # "id": checked_in_rental.id,
            "video_id": checked_in_rental.video_id,
            "customer_id": checked_in_rental.customer_id,
            "videos_checked_out_count": videos_checked_out_count,
            "available_inventory": available_inventory,
        }, 200
Example #26
0
def upload(vehiclePlate):
    vehicle=Vehicles.query.filter_by(vehiclePlate=vehiclePlate).first()
    path=vehicle.videos
    video=Video()
    alert=Alert()
    apikey=request.headers.get('Apikey')
    if vehicle and vehicle.apiKey ==apikey:
        os.chmod(path, stat.S_IWOTH)
        if request.method == 'POST':
            file = request.files['files']
            if file :
                try:
                   filename=time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())+ '.mp4'
                   video.carPlate=vehiclePlate
                   video.path=path+"/"+filename
                   video.uploadDate=time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
                   video.videoName=filename
                   file.save(path+"/"+filename)
                   message = " a new Alert Video uploads at" + video.uploadDate
                   alert.userid = vehicle.uid
                   alert.Plate = vehicle.vehiclePlate
                   alert.message = message
                   vehicle.videoNumber +=1
                   user=User.query.filter_by(id=vehicle.id).first()
                   video.uid =user.id
                   user.alertNumber += 1
                   db.session.add(user)
                   db.session.add(vehicle)
                   db.session.add(alert)
                   db.session.add(video)
                   db.session.commit()
                   return jsonify("successfully upload"),redirect(url_for('web.detection',videoname=video.videoName))
                except Exception as e:
                    db.session.rollback()
                    raise e

    return jsonify("Failure")
Example #27
0
def videos_show(video_id):
    video = Video.get_video_by_id(video_id)
    if not video:
        return {"message": f"Video {video_id} was not found"}, 404

    return video.to_json(), 200
Example #28
0
def videos_index():
    # newlist = [x for x in fruits if "a" in x]

    videos = [video.to_json() for video in Video.get_all_videos()]
    return jsonify(videos), 200