保利威视频播放

保利威视频播放

首先上线播放视频容易出的问题就是下载,以及盗录的问题,保利威视提供的API能够帮助我们解决这个问题~

解决下载的问题就是通过加密视频的形式,解决盗录是通过跑马灯的形式来实现的,那么我们来看下文档~到底要怎么做

注册账号,上传视频等

注册一个保利威的账号得到user_id以及secretKey

网站上还有上传以及视频设置等功能~~

加密以及跑马灯功能的实现

注意: 一定要仔细阅读文档~~特别是下面PHP代码的例子~~类比着实现~~

个人认为保利威文档写的不太清晰~一定要细心~~~~

播放加密视频的流程

1--播放加密视频需要在保利威视频播放器里加一个playsafe的参数

2--playsafe参数的值是token 也可以是一个function 这个function有两个参数

  一个是vid 一个是next  这个next方法必须被执行~ next(token) 而且要把token当做参数

3-- 那这个token到底是什么呢?

  这个token需要我们像保利威的接口发POST请求获取~

  接口地址是 https://hls.videocc.net/service/v1/token ~文档中有~

  发送POST请求带的参数是文档要求的~

  如果携带的参数对~这个接口会给我们返回验证通过的token~

  我们把token放入播放器的playsafe就可以播放了~~

播放跑马灯视频

播放跑马灯视频要求先必须用新的播放器~也就是引入新的js~

还有要在视频设置里配置一个回调的url~~

1--使用新的播放器去播放视频的时候,如果视频是授权跑马灯的,

  保利威会默认向你提供的回调接口发送GET请求~

2-- GET请求会携带一些参数,需要我们这个接口返回文档要求的信息~~

3-- 按照文档的实例来编写接口~成功后就可以播放视频~并且携带跑马灯~

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src='https://player.polyv.net/script/polyvplayer.min.js'></script>
    <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>

</head>
<body>

<div id="player"></div>



<script>
    var player = polyvObject('#player').videoPlayer({
                wrap: '#player',
                width: 800,
                height: 533,
                forceH5:true ,
                vid: '03b56854c0e149a81c1d6258be4d64c2_0',
                // vid: '03b56854c063c2132bd7de277de36e74_0',
                code: 'myRandomCodeValue',
               // 向后端发送请求获取加密的token
                playsafe: function (vid, next) {
                    console.log(vid);
                    axios.request({
                        url: "http://127.0.0.1:8002/api/course/polyv",
                        method: "POST",
                        data: {
                            vid: vid
                        }
                    }).then(function (data) {
                        console.log(data)
                        next(data.data)
                    })

                }
              });
</script>

</body>
</html>    
前端代码
import json
import time
import requests
import hashlib

from django.conf import settings


class PolyvVideo(object):

    USER_ID = settings.VIDEO_CONFIG["POLYV"]["USER_ID"]

    SECRET_KEY = settings.VIDEO_CONFIG["POLYV"]["SECRET_KEY"]

    def get_verify_data(self, vid, remote_addr, uid=None, username="", extra_params="HTML5"):
        """获取加密视频播放数据

        Parameters
        ----------
        vid : string
            视频 `vid`

        remote_addr: dict
            请求地址

        uid: string
            用户UID

        username: int
            用户username

        extra_params: string

            扩展参数

        Returns
        -------
        string
        """
        time_stamp = int(time.time() * 1000)

        # 加密数据
        sign_data = {
            "userId": self.USER_ID,
            "videoId": vid,
            "ts": time_stamp,
            "viewerIp": remote_addr,
            "viewerId": uid,
            "viewerName": username,
            "extraParams": extra_params
        }
        # 数据排序
        ordered_data = sorted(
            (
                (k, v if not isinstance(v, dict) else json.dumps(v, separators=(',', ':')))
                for k, v in sign_data.items()
            )
        )
        # 拼接加密数据
        sign_string = "{}{}{}".format(
            self.SECRET_KEY,
            "".join(["{}{}".format(item[0], item[1]) for item in ordered_data]),
            self.SECRET_KEY,
        )
        # 取大写的MD5值
        sign_data.update({"sign": self.generate_md5_num(sign_string).upper()})

        # 请求可以播放视频的凭证
        res = requests.post(
            url="https://hls.videocc.net/service/v1/token",
            headers={
                "Content-type": "application/x-www-form-urlencoded"
            },
            data=sign_data
        ).json()

        data = {} if isinstance(res, str) else res.get("data", {})

        return {
            "token": data.get("token"),
            # "sign": self.generate_md5_num("{}{}{}".format(self.SECRET_KEY, vid, time_stamp)),
            # "time_stamp": time_stamp
        }

    def generate_md5_num(self, value):
        return hashlib.md5(value.encode()).hexdigest()

    def get_play_key(self, vid, username, code, status, t):
        """获取授权跑马灯播放 `key`

        Parameters
        ----------
        vid : string
            视频 `vid`

        username: dict
            响应跑马灯展示

        code: string
            自定义参数

        status: int

            是否可播放,  1、可播放 2、禁播

        t: string

            时间戳

        Returns
        -------
        string
        """
        return self.generate_md5_num("vid={}&secretkey={}&username={}&code={}&status={}&t={}".format(
            vid, self.SECRET_KEY, username, code, status, t
        )).lower()

    @staticmethod
    def get_resp(status, username, sign, msg="授权暂未通过"):
        res_str = {
            "status": status,
            "username": username,
            "sign": sign,
            "msg": msg,
            "fontSize": "18",
            "fontColor": "0xFF0000",
            "speed": "50",
            "filter": "on",
            "setting": "2",
            "alpha": "0.7",
            "filterAlpha": "1",
            "filterColor": "0x3914AF",
            "blurX": "2",
            "blurY": "2",
            "tweenTime": "1",
            "interval": "3",
            "lifeTime": "3",
            "strength": "4",
            "show": "on"
        }
        return res_str


polyv_video = PolyvVideo()
polyv.py
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 课程模块的路由分发
    url(r'^api/course/', include("course.urls")),
    url(r'^crossdomain.xml', test_bolyv),
]

// courseAPP下的urls.py
# by gaoxin
from django.conf.urls import url, include
from .views import CourseListView, CourseCategoryView, CourseDetailView, CourseChapterView
from .views import CourseCommentView, OftenAskedQuestionView, polyv_demo
from .video_view import PolyvView


# 在项目路由下做了一层分发
# url(r'^api/course/', include("course.urls")),
urlpatterns = [
    url(r"^$", CourseListView.as_view()),
    url(r"^category$", CourseCategoryView.as_view()),
    url(r"^detail/(?P<pk>\d+)$", CourseDetailView.as_view()),
    url(r"^(?P<pk>\d+)/chapters$", CourseChapterView.as_view()),
    url(r"^(?P<pk>\d+)/comment$", CourseCommentView.as_view()),
    url(r"^(?P<pk>\d+)/often-asked-question$", OftenAskedQuestionView.as_view()),
    # 获取加密数据播放视频post请求
    # 获取授权跑马灯回调的get接口
    url(r"^polyv$", PolyvView.as_view())
]
urls.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse
from utils.polyv import polyv_video
from utils.authentication import MyAuth
import json


class PolyvView(APIView):

    def post(self, request):
        vid = request.data.get("vid")
        remote_addr = request.META.get("REMOTE_ADDR")
        user_id = 1
        user_name = "gaoxin"
        verify_data = polyv_video.get_verify_data(vid, remote_addr, user_id, user_name)
        return Response(verify_data["token"])

    def get(self, request, *args, **kwargs):
        vid = request.query_params.get("vid", "")
        code = request.query_params.get("code", "")
        t = request.query_params.get("t", "")
        callback = request.query_params.get("callback", "")
        user_name = "peng"
        status = 1
        # username, code, status, t
        sign = polyv_video.get_play_key(vid, user_name, code, status, t)
        print(sign)
        res_str = polyv_video.get_resp(int(status), user_name, sign)
        res_str = json.dumps(res_str, ensure_ascii=False)
        if callback != "":
            ret = callback + "(" + res_str + ")"
        else:
            ret = res_str
        print(ret)
        return HttpResponse(ret)


# 解决跨域
def test_bolyv(request):
    return render(request, "bolyv_test.html")
views.py
<cross-domain-policy>
<allow-access-from domain="*.polyv.net"/>
</cross-domain-policy>
跨域的html文件

 

特别注意: 

  不能用Response 只能用HttpResponse

  以及代码中哪些字符串加密成sign

posted @ 2018-12-22 23:22  温而新  阅读(1466)  评论(0编辑  收藏  举报