From e9f6bf0c4a1143e614ccf307b6677a84827cdf13 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 21 Mar 2018 10:54:56 +0800 Subject: [PATCH 01/37] fix historyactivity --- example.py | 113 ------------------------------ live_examples/bandwidth_count.py | 8 +-- live_examples/convert.py | 9 ++- live_examples/create_steam.py | 10 ++- live_examples/history_record.py | 17 +++-- live_examples/publish_play_url.py | 22 +++--- live_examples/save_playback.py | 9 +-- pili/__init__.py | 4 +- pili/api.py | 17 ++++- pili/auth.py | 20 ++++++ pili/client.py | 9 --- pili/compat.py | 77 ++++++++++++++++++++ pili/stream.py | 14 +++- 13 files changed, 163 insertions(+), 166 deletions(-) delete mode 100644 example.py delete mode 100644 pili/client.py create mode 100644 pili/compat.py diff --git a/example.py b/example.py deleted file mode 100644 index 7b74314..0000000 --- a/example.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- - -import os -import random -import sys -import time - -import pili - - -def env(key): - if key in os.environ: - return os.environ[key] - else: - return "" - - -if __name__ == "__main__": - if env("PILI_API_HOST") != "": - pili.conf.API_HOST = env("PILI_API_HOST") - - access_key = env("QINIU_ACCESS_KEY") - secret_key = env("QINIU_SECRET_KEY") - if access_key == "" or secret_key == "": - print "need set access_key and secret_key" - sys.exit(1) - - mac = pili.Mac(access_key, secret_key) - - hub_name = "PiliSDKTest" - - client = pili.Client(mac) - hub = client.hub(hub_name) - - stream_pre = "stream2" + str(int(random.random()*1e10)) - stream_title1 = stream_pre + "_1" - stream_title2 = stream_pre + "_2" - stream_title3 = stream_pre + "_3" - - stream = hub.create(stream_title1) - print "create stream:" - print stream - - print "get stream:" - stream = hub.get(stream_title1) - print stream - - print "get stream info:" - stream = hub.get(stream_title1) - print stream.refresh() - - stream = hub.create(stream_title2) - print "create another stream:" - print stream - - hub.create(stream_title3) - - print "list streams:" - print hub.list(prefix=stream_pre, limit=2) - - print "list live streams:" - print hub.list(liveonly=True) - - print "batch query live streams:" - print hub.batch_live_status(["test1", "test2"]) - - stream = hub.get(stream_title1) - print "before disable:", stream, stream.disabled() - stream.disable(int(time.time()) + 5) - print "after call disable:", stream.refresh(), stream.disabled() - time.sleep(5) - print "after sleep 5 seconds:", stream.refresh(), stream.disabled() - - stream = hub.get(stream_title1) - stream.disable() - print "before enable:", stream.refresh(), stream.disabled() - stream.enable() - print "after enable:", stream.refresh(), stream.disabled() - - stream = hub.get(stream_title1) - print "before update converts:", stream.refresh() - stream.update_converts(["480p", "720p"]) - print "after update converts:", stream.refresh() - - stream = hub.get("test1") - print "query stream live status:" - print stream.status() - - now = int(time.time()) - print "save stream playback:" - print stream.saveas(start_second=now-300, fname="test1.m3u8") - - print "save stream snapshot:" - print stream.snapshot(fname="test1.jpg") - - now = int(time.time()) - print "get publish history:" - print stream.history(start_second=now-86400) - - print "RTMP publish URL:" - print pili.rtmp_publish_url("publish-rtmp.test.com", hub_name, "streamtitle", mac, 60) - - print "RTMP play URL:" - print pili.rtmp_play_url("live-rtmp.test.com", hub_name, "streamtitle") - - print "HLS live URL:" - print pili.hls_play_url("live-hls.test.com", hub_name, "streamtitle") - - print "HDL live URL:" - print pili.hdl_play_url("live-hdl.test.com", hub_name, "streamtitle") - - print "snapshot URL:" - print pili.snapshot_play_url("live-snapshot.test.com", hub_name, "streamtitle") diff --git a/live_examples/bandwidth_count.py b/live_examples/bandwidth_count.py index 1534bd8..4b481a6 100644 --- a/live_examples/bandwidth_count.py +++ b/live_examples/bandwidth_count.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pili +from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey access_key = "..." @@ -10,10 +10,10 @@ secret_key = "..." hub_name = '...' -mac = pili.Mac(access_key, secret_key) -client = pili.Client(mac) -hub = client.hub(hub_name) +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) print hub.bandwidth_count_now() diff --git a/live_examples/convert.py b/live_examples/convert.py index 8930274..2f06a29 100644 --- a/live_examples/convert.py +++ b/live_examples/convert.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pili +from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey access_key = "..." @@ -8,12 +8,11 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '' -mac = pili.Mac(access_key, secret_key) -client = pili.Client(mac) +hub_name = '...' -hub = client.hub(hub_name) +mac = Mac(access_key, secret_key) +hub = Hub(mac, hub_name) stream = hub.get("") print(stream.update_converts(["480p", "720p"])) diff --git a/live_examples/create_steam.py b/live_examples/create_steam.py index 889ffbf..d487f74 100644 --- a/live_examples/create_steam.py +++ b/live_examples/create_steam.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pili +from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey access_key = "..." @@ -8,14 +8,12 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." - hub_name = '' -stream_name = '' -mac = pili.Mac(access_key, secret_key) +stream_name = '' -client = pili.Client(mac) +mac = Mac(access_key, secret_key) -hub = client.hub(hub_name) +hub = Hub(mac, hub_name) hub.create(stream_name) diff --git a/live_examples/history_record.py b/live_examples/history_record.py index a5aaaa7..3f08424 100644 --- a/live_examples/history_record.py +++ b/live_examples/history_record.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pili +from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey access_key = "..." @@ -12,11 +12,16 @@ hub_name = '...' -stream_name = '...' +stream_name = '123' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) -mac = pili.Mac(access_key, secret_key) -client = pili.Client(mac) -hub = client.hub(hub_name) stream = hub.get(stream_name) -print(stream.history(start_second=0, end_second=0)) +resp = stream.history(start_second=0, end_second=0) + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/live_examples/publish_play_url.py b/live_examples/publish_play_url.py index f66a2fb..8b2ad6d 100644 --- a/live_examples/publish_play_url.py +++ b/live_examples/publish_play_url.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pili +from pili import Mac, Hub, rtmp_play_url, rtmp_publish_url, hdl_play_url, hls_play_url, snapshot_play_url # 替换成自己 Qiniu 账号的 AccessKey access_key = "..." @@ -12,25 +12,23 @@ hub_name = '...' -stream_title = '...' +stream_name = '...' expire = 3600 -mac = pili.Mac(access_key, secret_key) -client = pili.Client(mac) +mac = Mac(access_key, secret_key) -hub = client.hub(hub_name) +hub = Hub(mac, hub_name) +stream = hub.get(stream_name) -stream = hub.get("...") +print rtmp_publish_url(domain, hub_name, stream_name, mac, expire) -print pili.rtmp_publish_url(domain, hub_name, stream_title, mac, expire) +print rtmp_play_url(domain, hub_name, stream_name) -print pili.rtmp_play_url(domain, hub_name, stream_title) +print hls_play_url(domain, hub_name, stream_name) -print pili.hls_play_url(domain, hub_name, stream_title) +print hdl_play_url(domain, hub_name, stream_name) -print pili.hdl_play_url(domain, hub_name, stream_title) - -print pili.snapshot_play_url(domain, hub_name, stream_title) +print snapshot_play_url(domain, hub_name, stream_name) diff --git a/live_examples/save_playback.py b/live_examples/save_playback.py index 4451c85..de60a10 100644 --- a/live_examples/save_playback.py +++ b/live_examples/save_playback.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pili +from pili import Mac, Hub access_key = "..." @@ -15,9 +15,10 @@ fname = 'example_fname.mp4' -mac = pili.Mac(access_key, secret_key) -client = pili.Client(mac) -hub = client.hub(hub_name) +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + stream = hub.get(stream_name) print(stream.saveas(start_second=0, end_second=0, format='mp4', fname=fname)) diff --git a/pili/__init__.py b/pili/__init__.py index 17c1f57..d71851a 100644 --- a/pili/__init__.py +++ b/pili/__init__.py @@ -1,6 +1,6 @@ from .errors import APIError # noqa from .auth import Mac # noqa -from .client import Client # noqa from .urls import rtmp_publish_url, rtmp_play_url, hls_play_url, hdl_play_url, snapshot_play_url # noqa import conf # noqa -from .roomClient import RoomClient # noqa \ No newline at end of file +from .roomClient import RoomClient # noqa +from .hub import Hub # noqa \ No newline at end of file diff --git a/pili/api.py b/pili/api.py index 33fda61..9172a2c 100644 --- a/pili/api.py +++ b/pili/api.py @@ -1,8 +1,10 @@ from .auth import auth_interface import pili.conf as conf -from urllib2 import Request +from requests import Request +import requests import json import base64 +from compat import urlparse def normalize(args, keyword): @@ -119,6 +121,7 @@ def stream_snapshot(hub, key, **kwargs): return Request(url=url, data=encoded) + @auth_interface def get_history(hub, key, **kwargs): keyword = ['start', 'end'] @@ -127,7 +130,10 @@ def get_history(hub, key, **kwargs): url = "http://%s/%s/hubs/%s/streams/%s/historyactivity?" % (conf.API_HOST, conf.API_VERSION, hub, key) for k, v in args.items(): url += "&%s=%s" % (k, v) - return Request(url=url) + r = Request(url=url) + print r.url + + # return requests.get(url=url) @auth_interface @@ -158,3 +164,10 @@ def bandwidth_count_history(hub, **kwargs): def bandwidth_count_detail(hub, time): url = "http://%s/%s/hubs/%s/stat/play/history/detail?time=%s" % (conf.API_HOST, conf.API_VERSION, hub, time) return Request(url=url) + + +def _get(url, auth): + + hearders = auth.authed("GET", url) + return requests.get(url=url, headers=hearders) + diff --git a/pili/auth.py b/pili/auth.py index 85f1511..bdbb721 100644 --- a/pili/auth.py +++ b/pili/auth.py @@ -31,6 +31,25 @@ def auth_interface_str(self, raw_str): encoded = __hmac_sha1__(raw_str, self.secret_key) return 'Qiniu {0}:{1}'.format(self.access_key, encoded) + def authed(self, method, url, body=None): + headers = {} + + parsed = urlparse(url) + raw_str = '%s %s' % (method, parsed.path) + if parsed.query: + raw_str += '?%s' % parsed.query + raw_str += '\nHost: %s' % parsed.netloc + if body: + raw_str += '\nContent-Type: application/json' + raw_str += "\n\n" + raw_str += body + headers.update({'Content-Type': 'application/json'}) + else: + raw_str += "\n\n" + headers.update({'Authorization': self.auth_interface_str(raw_str)}) + headers.update({'User-Agent': conf.API_USERAGENT}) + return headers + def auth_interface(method): """ @@ -48,6 +67,7 @@ def authed(auth, **args): send request and decode response. Return the result in python format. """ req = method(**args) + parsed = urlparse(req.get_full_url()) raw_str = '%s %s' % (req.get_method(), parsed.path) if parsed.query: diff --git a/pili/client.py b/pili/client.py deleted file mode 100644 index 7160e0b..0000000 --- a/pili/client.py +++ /dev/null @@ -1,9 +0,0 @@ -from .hub import Hub - - -class Client(object): - def __init__(self, mac): - self.__mac__ = mac - - def hub(self, hub): - return Hub(self.__mac__, hub) diff --git a/pili/compat.py b/pili/compat.py new file mode 100644 index 0000000..3333a58 --- /dev/null +++ b/pili/compat.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +""" +pythoncompat +""" + +import sys + +try: + import simplejson as json +except (ImportError, SyntaxError): + # simplejson does not support Python 3.2, it thows a SyntaxError + # because of u'...' Unicode literals. + import json # noqa + + +# ------- +# Pythons +# ------- + +_ver = sys.version_info + +#: Python 2.x? +is_py2 = (_ver[0] == 2) + +#: Python 3.x? +is_py3 = (_ver[0] == 3) + + +# --------- +# Specifics +# --------- + +if is_py2: + from urlparse import urlparse # noqa + import StringIO + StringIO = BytesIO = StringIO.StringIO + + builtin_str = str + bytes = str + str = unicode # noqa + basestring = basestring # noqa + numeric_types = (int, long, float) # noqa + + def b(data): + return bytes(data) + + def s(data): + return bytes(data) + + def u(data): + return unicode(data, 'unicode_escape') # noqa + +elif is_py3: + from urllib.parse import urlparse # noqa + import io + StringIO = io.StringIO + BytesIO = io.BytesIO + + builtin_str = str + str = str + bytes = bytes + basestring = (str, bytes) + numeric_types = (int, float) + + def b(data): + if isinstance(data, str): + return data.encode('utf-8') + return data + + def s(data): + if isinstance(data, bytes): + data = data.decode('utf-8') + return data + + def u(data): + return data diff --git a/pili/stream.py b/pili/stream.py index 96fbc4f..93dcf19 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -2,8 +2,9 @@ import json import time - +from base64 import urlsafe_b64encode import pili.api as api +import conf class Stream(object): @@ -82,8 +83,15 @@ def status(self): end: Unix时间戳,直播结束时间 """ def history(self, start_second=None, end_second=None): - res = api.get_history(self.__auth__, hub=self.hub, key=self.key, start=start_second, end=end_second) - return res["items"] + # res = api.get_history(self.__auth__, hub=self.hub, key=self.key, start=start_second, end=end_second) + + key = urlsafe_b64encode(self.key) + url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(conf.API_HOST, conf.API_VERSION, self.hub, key) + if start_second != None: + url += "&start={}".format(start_second) + if end_second != None: + url += "&end={}".format(end_second) + return api._get(url, self.__auth__) # save_as等同于saveas接口,出于兼容考虑,暂时保留 def save_as(self, start_second=None, end_second=None, **kwargs): From 7535dcaf08b547400108ec738f26323664b3bb98 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 21 Mar 2018 11:09:49 +0800 Subject: [PATCH 02/37] fix convert --- live_examples/convert.py | 12 ++++++++++-- live_examples/history_record.py | 10 ++++------ pili/api.py | 6 +++++- pili/stream.py | 14 ++++++++------ 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/live_examples/convert.py b/live_examples/convert.py index 2f06a29..25c84c1 100644 --- a/live_examples/convert.py +++ b/live_examples/convert.py @@ -14,5 +14,13 @@ hub = Hub(mac, hub_name) -stream = hub.get("") -print(stream.update_converts(["480p", "720p"])) +stream = hub.get("123") + +resp = stream.update_converts(["480p", "720p"]) + +# 建议打印headers方便向官方反馈问题,该接口调用成功是放回json为空{} +print(resp.status_code) +print(resp.headers) +print(resp.text) + + diff --git a/live_examples/history_record.py b/live_examples/history_record.py index 3f08424..840e091 100644 --- a/live_examples/history_record.py +++ b/live_examples/history_record.py @@ -3,14 +3,12 @@ from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey -access_key = "..." - +access_key = "Y93_QIW2j-Bw84R7M07Mnno0re7TcEFq1InWpc9J" # 替换成自己 Qiniu 账号的 SecretKey -secret_key = "..." - +secret_key = "BVclqX13x3uhr099JXcrfZS__wyF2fUnBFW4Kj5G" -hub_name = '...' +hub_name = 'berniezhibo' stream_name = '123' @@ -20,7 +18,7 @@ stream = hub.get(stream_name) -resp = stream.history(start_second=0, end_second=0) +resp = stream.history(start_second=3123123, end_second=3123123123) print(resp.status_code) print(resp.headers) diff --git a/pili/api.py b/pili/api.py index 9172a2c..9304717 100644 --- a/pili/api.py +++ b/pili/api.py @@ -167,7 +167,11 @@ def bandwidth_count_detail(hub, time): def _get(url, auth): - hearders = auth.authed("GET", url) return requests.get(url=url, headers=hearders) + +def _post(url, auth, data): + hearders = auth.authed("POST", url, body=data) + return requests.post(url=url, headers=hearders, data=data) + diff --git a/pili/stream.py b/pili/stream.py index 93dcf19..306703d 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -83,13 +83,11 @@ def status(self): end: Unix时间戳,直播结束时间 """ def history(self, start_second=None, end_second=None): - # res = api.get_history(self.__auth__, hub=self.hub, key=self.key, start=start_second, end=end_second) - key = urlsafe_b64encode(self.key) url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(conf.API_HOST, conf.API_VERSION, self.hub, key) - if start_second != None: + if start_second: url += "&start={}".format(start_second) - if end_second != None: + if end_second: url += "&end={}".format(end_second) return api._get(url, self.__auth__) @@ -146,8 +144,12 @@ def snapshot(self, **kwargs): 返回值: 无 """ def update_converts(self, profiles=[]): - res = api.update_stream_converts(self.__auth__, hub=self.hub, key=self.key, profiles=profiles) - return res + # res = api.update_stream_converts(self.__auth__, hub=self.hub, key=self.key, profiles=profiles) + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s/converts" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + encoded_data = json.dumps({"converts": profiles}) + return api._post(url, self.__auth__, data=encoded_data) + def to_json(self): return json.dumps(self.data) From a1e671210d6a5b43a53c28dfcaa29dbcbe91eb8a Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 21 Mar 2018 11:44:01 +0800 Subject: [PATCH 03/37] fix bandwidth --- live_examples/bandwidth_count.py | 11 +++++++---- live_examples/history_record.py | 8 ++++---- pili/api.py | 2 +- pili/hub.py | 16 ++++++++++------ pili/stream.py | 18 ++++++++---------- pili/utils.py | 14 ++++++++++++++ 6 files changed, 44 insertions(+), 25 deletions(-) diff --git a/live_examples/bandwidth_count.py b/live_examples/bandwidth_count.py index 4b481a6..ac39e96 100644 --- a/live_examples/bandwidth_count.py +++ b/live_examples/bandwidth_count.py @@ -5,7 +5,6 @@ # 替换成自己 Qiniu 账号的 AccessKey access_key = "..." - # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." @@ -15,8 +14,12 @@ hub = Hub(mac, hub_name) -print hub.bandwidth_count_now() +resp = hub.bandwidth_count_now() + +# resp = hub.bandwidth_count_detail(1512616339) -# print hub.bandwidth_count_detail(1512616339) +# resp = hub.bandwidth_count_history() -# print hub.bandwidth_count_history(1512616339, 1512616439) +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/live_examples/history_record.py b/live_examples/history_record.py index 840e091..663b3c5 100644 --- a/live_examples/history_record.py +++ b/live_examples/history_record.py @@ -3,12 +3,12 @@ from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey -access_key = "Y93_QIW2j-Bw84R7M07Mnno0re7TcEFq1InWpc9J" +access_key = "..." # 替换成自己 Qiniu 账号的 SecretKey -secret_key = "BVclqX13x3uhr099JXcrfZS__wyF2fUnBFW4Kj5G" +secret_key = "..." -hub_name = 'berniezhibo' +hub_name = '...' stream_name = '123' @@ -18,7 +18,7 @@ stream = hub.get(stream_name) -resp = stream.history(start_second=3123123, end_second=3123123123) +resp = stream.history(start=1513616430, end=1513616400) print(resp.status_code) print(resp.headers) diff --git a/pili/api.py b/pili/api.py index 9304717..f5ccb7c 100644 --- a/pili/api.py +++ b/pili/api.py @@ -154,7 +154,7 @@ def bandwidth_count_now(hub): def bandwidth_count_history(hub, **kwargs): keyword = ['start', 'end', 'limit', 'marker'] args = normalize(kwargs, keyword) - url = "http://%s/%s/hubs/%s/stat/play/history" % (conf.API_HOST, conf.API_VERSION, hub) + url = "http://%s/%s/hubs/%s/stat/play/history?" % (conf.API_HOST, conf.API_VERSION, hub) for k, v in args.items(): url += "&%s=%s" % (k, v) return Request(url=url) diff --git a/pili/hub.py b/pili/hub.py index e280dda..8b9c59e 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -2,6 +2,8 @@ import pili.api as api from .stream import Stream +from conf import API_HOST, API_VERSION +from utils import normalize_path class Hub(object): @@ -52,13 +54,15 @@ def batch_live_status(self, streams): return res["items"] def bandwidth_count_now(self): - res = api.bandwidth_count_now(self.__auth__, hub=self.__hub__) - return res + url = "http://%s/%s/hubs/%s/stat/play" % (API_HOST, API_VERSION, self.__hub__) + return api._get(url, self.__auth__) - def bandwidth_count_history(self, start, end, limit=None, marker=None): - res = api.bandwidth_count_history(self.__auth__, hub=self.__hub__, start=start, end=end, limit=limit, - marker=marker) - return res + def bandwidth_count_history(self, **kwargs): + url = "http://%s/%s/hubs/%s/stat/play/history?" % (API_HOST, API_VERSION, self.__hub__) + keyword = ['start', 'end', 'limit', 'marker'] + url = normalize_path(kwargs, keyword, url) + + return api._get(url=url, auth=self.__auth__) def bandwidth_count_detail(self, time): res = api.bandwidth_count_detail(self.__auth__, hub=self.__hub__, time=time) diff --git a/pili/stream.py b/pili/stream.py index 306703d..7f392a8 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -5,6 +5,7 @@ from base64 import urlsafe_b64encode import pili.api as api import conf +from utils import normalize_path class Stream(object): @@ -76,19 +77,17 @@ def status(self): """ history 查询直播历史 输入参数: - start_second: Unix时间戳,起始时间,可选,默认不限制起始时间 - end_second: Unix时间戳,结束时间,可选,默认为当前时间 + start: Unix时间戳,起始时间,可选,默认不限制起始时间 + end: Unix时间戳,结束时间,可选,默认为当前时间 返回值: 如下结构的数组 start: Unix时间戳,直播开始时间 end: Unix时间戳,直播结束时间 """ - def history(self, start_second=None, end_second=None): + def history(self, **kwargs): key = urlsafe_b64encode(self.key) + keyword = ['start', 'end'] url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(conf.API_HOST, conf.API_VERSION, self.hub, key) - if start_second: - url += "&start={}".format(start_second) - if end_second: - url += "&end={}".format(end_second) + url = normalize_path(kwargs, keyword, url) return api._get(url, self.__auth__) # save_as等同于saveas接口,出于兼容考虑,暂时保留 @@ -98,8 +97,8 @@ def save_as(self, start_second=None, end_second=None, **kwargs): """ saveas 保存直播回放到存储空间 输入参数: - start_second: Unix时间戳,起始时间,可选,默认不限制起始时间 - end_second: Unix时间戳,结束时间,可选,默认为当前时间 + start: Unix时间戳,起始时间,可选,默认不限制起始时间 + end: Unix时间戳,结束时间,可选,默认为当前时间 fname: 保存的文件名,可选,不指定会随机生产 format: 保存的文件格式,可选,默认为m3u8,如果指定其他格式则保存动作为异步模式 pipeline: dora的私有队列,可选,不指定则使用默认队列 @@ -144,7 +143,6 @@ def snapshot(self, **kwargs): 返回值: 无 """ def update_converts(self, profiles=[]): - # res = api.update_stream_converts(self.__auth__, hub=self.hub, key=self.key, profiles=profiles) key = urlsafe_b64encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/converts" % (conf.API_HOST, conf.API_VERSION, self.hub, key) encoded_data = json.dumps({"converts": profiles}) diff --git a/pili/utils.py b/pili/utils.py index 6fa861b..c6b6dc1 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -55,3 +55,17 @@ def s(data): def urlsafe_base64_encode(data): ret = base64.urlsafe_b64encode(b(data)) return s(ret) + + +def normalize_path(args, keyword, url): + if set(args) - set(keyword): + raise ValueError('invalid key') + for k, v in args.items(): + if v is None: + del args[k] + path = '' + for k, v in args.items(): + path += "&%s=%s" % (k, v) + if path: + url = url + '?' + path + return url From 6f699418ad31ca81b3335603af71814539ec6481 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 21 Mar 2018 11:44:54 +0800 Subject: [PATCH 04/37] change example --- live_examples/bandwidth_count.py | 6 +++--- live_examples/create_steam.py | 7 ++++++- pili/hub.py | 6 +++--- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/live_examples/bandwidth_count.py b/live_examples/bandwidth_count.py index ac39e96..795a9e8 100644 --- a/live_examples/bandwidth_count.py +++ b/live_examples/bandwidth_count.py @@ -14,11 +14,11 @@ hub = Hub(mac, hub_name) -resp = hub.bandwidth_count_now() - +# resp = hub.bandwidth_count_now() +# # resp = hub.bandwidth_count_detail(1512616339) -# resp = hub.bandwidth_count_history() +resp = hub.bandwidth_count_history(start=1512616339, end=1512616400, limit=100, marker=None) print(resp.status_code) print(resp.headers) diff --git a/live_examples/create_steam.py b/live_examples/create_steam.py index d487f74..9c88515 100644 --- a/live_examples/create_steam.py +++ b/live_examples/create_steam.py @@ -16,4 +16,9 @@ hub = Hub(mac, hub_name) -hub.create(stream_name) +resp = hub.create(stream_name) + + +print(resp.status_code) +print(resp.headers) +print(resp.text) \ No newline at end of file diff --git a/pili/hub.py b/pili/hub.py index 8b9c59e..6520eab 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -61,9 +61,9 @@ def bandwidth_count_history(self, **kwargs): url = "http://%s/%s/hubs/%s/stat/play/history?" % (API_HOST, API_VERSION, self.__hub__) keyword = ['start', 'end', 'limit', 'marker'] url = normalize_path(kwargs, keyword, url) - return api._get(url=url, auth=self.__auth__) def bandwidth_count_detail(self, time): - res = api.bandwidth_count_detail(self.__auth__, hub=self.__hub__, time=time) - return res + url = "http://%s/%s/hubs/%s/stat/play/history/detail?time=%s" % (API_HOST, API_VERSION, self.__hub__, time) + return api._get(url, self.__auth__) + From b4b14601b54a431051af757fe5946dea61371247 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 21 Mar 2018 12:10:19 +0800 Subject: [PATCH 05/37] create stream --- live_examples/create_steam.py | 11 ++++++----- pili/hub.py | 13 ++++++++----- pili/stream.py | 4 +++- pili/utils.py | 8 ++++++++ 4 files changed, 25 insertions(+), 11 deletions(-) diff --git a/live_examples/create_steam.py b/live_examples/create_steam.py index 9c88515..9a47f9f 100644 --- a/live_examples/create_steam.py +++ b/live_examples/create_steam.py @@ -8,17 +8,18 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '' +hub_name = '...' -stream_name = '' +stream_name = '...' mac = Mac(access_key, secret_key) hub = Hub(mac, hub_name) -resp = hub.create(stream_name) - +resp = hub.create(key=stream_name) print(resp.status_code) print(resp.headers) -print(resp.text) \ No newline at end of file +print(resp.text) + +print(hub.get(stream_name)) diff --git a/pili/hub.py b/pili/hub.py index 6520eab..e7baef1 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -3,8 +3,8 @@ import pili.api as api from .stream import Stream from conf import API_HOST, API_VERSION -from utils import normalize_path - +from utils import normalize_path, normalize_data +import json class Hub(object): def __init__(self, mac, hub): @@ -12,9 +12,12 @@ def __init__(self, mac, hub): self.__hub__ = hub # create 创建一路流 - def create(self, key): - api.create_stream(self.__auth__, hub=self.__hub__, key=key) - return Stream(self.__auth__, hub=self.__hub__, key=key) + def create(self, **kwargs): + keyword = ['key'] + url = "http://%s/%s/hubs/%s/streams" % (API_HOST, API_VERSION, self.__hub__) + encoded = normalize_data(kwargs, keyword) + return api._post(url=url, auth=self.__auth__, data=encoded) + # 获取一路流 def get(self, key): diff --git a/pili/stream.py b/pili/stream.py index 7f392a8..f335ce2 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -37,7 +37,9 @@ def __repr__(self): # refresh 主动更新流信息,会产生一次rpc调用 def refresh(self): - data = api.get_stream(self.__auth__, hub=self.hub, key=self.key) + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + data = api._get(url=url, auth=self.__auth__) self.__data__ = {} for p in ["disabledTill", "converts"]: self.__data__[p] = data[p] if p in data else None diff --git a/pili/utils.py b/pili/utils.py index c6b6dc1..84d0455 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -69,3 +69,11 @@ def normalize_path(args, keyword, url): if path: url = url + '?' + path return url + +def normalize_data(args, keyword): + if set(args) - set(keyword): + raise ValueError('invalid key') + for k, v in args.items(): + if v is None: + del args[k] + return json.dumps(args) \ No newline at end of file From 803b6a620bde350ddb68e95b498c32535693c21c Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 10:56:21 +0800 Subject: [PATCH 06/37] fix saveas --- live_examples/save_playback.py | 15 +++++++++------ pili/api.py | 2 ++ pili/stream.py | 18 ++++++++---------- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/live_examples/save_playback.py b/live_examples/save_playback.py index de60a10..0d6caf9 100644 --- a/live_examples/save_playback.py +++ b/live_examples/save_playback.py @@ -2,18 +2,17 @@ from pili import Mac, Hub +# 替换成自己 Qiniu 账号的 AccessKey access_key = "..." - # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." +hub_name = '...' -hub_name = "..." - -stream_name = "..." +stream_name = "123" -fname = 'example_fname.mp4' +fname = 'example_fname.m3u8' mac = Mac(access_key, secret_key) @@ -21,4 +20,8 @@ stream = hub.get(stream_name) -print(stream.saveas(start_second=0, end_second=0, format='mp4', fname=fname)) +resp = stream.saveas(start=0, end=0, format='m3u8', fname=fname) + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/pili/api.py b/pili/api.py index f5ccb7c..f479164 100644 --- a/pili/api.py +++ b/pili/api.py @@ -167,11 +167,13 @@ def bandwidth_count_detail(hub, time): def _get(url, auth): + print("get") hearders = auth.authed("GET", url) return requests.get(url=url, headers=hearders) def _post(url, auth, data): + print("post") hearders = auth.authed("POST", url, body=data) return requests.post(url=url, headers=hearders, data=data) diff --git a/pili/stream.py b/pili/stream.py index f335ce2..d0a262f 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -5,7 +5,7 @@ from base64 import urlsafe_b64encode import pili.api as api import conf -from utils import normalize_path +from utils import normalize_path, normalize_data class Stream(object): @@ -113,15 +113,13 @@ def save_as(self, start_second=None, end_second=None, **kwargs): fname: 保存到存储空间的文件名 persistentID: 异步模式时,持久化异步处理任务ID,通常用不到该字段 """ - def saveas(self, start_second=None, end_second=None, **kwargs): - kwargs["hub"] = self.hub - kwargs["key"] = self.key - if start_second is not None: - kwargs["start"] = start_second - if end_second is not None: - kwargs["end"] = end_second - res = api.stream_saveas(self.__auth__, **kwargs) - return res + def saveas(self, **kwargs): + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] + encoded_data = normalize_data(kwargs, keyword) + return api._post(url, self.__auth__, data=encoded_data) + """ snapshot 保存直播截图到存储空间 From d6030be6d66deac78c35e626d9fbd8bfbf71debf Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 11:13:11 +0800 Subject: [PATCH 07/37] fix url.. --- live_examples/publish_play_url.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/live_examples/publish_play_url.py b/live_examples/publish_play_url.py index 8b2ad6d..dfbb5cc 100644 --- a/live_examples/publish_play_url.py +++ b/live_examples/publish_play_url.py @@ -8,11 +8,11 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -domain = '...' - hub_name = '...' -stream_name = '...' +domain = '...' + +stream_name = '123' expire = 3600 @@ -22,13 +22,17 @@ stream = hub.get(stream_name) - +""" +该生成推流地址方法只适用于v2版本的限时鉴权,v2的无鉴权只需拼接域名,直播空间名和流名,v1版本的鉴权算法见下 +https://developer.qiniu.com/pili/kb/1332/broadcast-authentication-mode +https://developer.qiniu.com/pili/kb/2635/seven-cows-live-push-flow-authentication-md +""" print rtmp_publish_url(domain, hub_name, stream_name, mac, expire) -print rtmp_play_url(domain, hub_name, stream_name) - -print hls_play_url(domain, hub_name, stream_name) - -print hdl_play_url(domain, hub_name, stream_name) - -print snapshot_play_url(domain, hub_name, stream_name) +# print rtmp_play_url(domain, hub_name, stream_name) +# +# print hls_play_url(domain, hub_name, stream_name) +# +# print hdl_play_url(domain, hub_name, stream_name) +# +# print snapshot_play_url(domain, hub_name, stream_name) From 3711d373cf00beea047a22e2702a2c88a20ed4f4 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 11:50:25 +0800 Subject: [PATCH 08/37] add list stream --- live_examples/streams.py | 22 ++++++++++++++++++++++ pili/hub.py | 7 +++++-- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 live_examples/streams.py diff --git a/live_examples/streams.py b/live_examples/streams.py new file mode 100644 index 0000000..293dfdc --- /dev/null +++ b/live_examples/streams.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.list() + +print(resp.status_code) +print(resp.headers) +print(resp.text) + diff --git a/pili/hub.py b/pili/hub.py index e7baef1..7a7f278 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -35,8 +35,11 @@ def get(self, key): marker: 这次遍历得到的游标,下次请求应该带上,如果为"",则表示已遍历完所有流 """ def list(self, **kwargs): - res = api.get_stream_list(self.__auth__, hub=self.__hub__, **kwargs) - return res + url = "http://%s/%s/hubs/%s/streams?" % (API_HOST, API_VERSION, self.__hub__) + keyword = ['liveonly', 'prefix', 'limit', 'marker'] + url = normalize_path(kwargs, keyword, url) + return api._get(url=url, auth=self.__auth__) + """ batch_live_status 批量查询流的直播信息 From 5ea292305e14890158d75608daef5b54acfb3a36 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 13:29:20 +0800 Subject: [PATCH 09/37] add stream --- live_examples/stream.py | 23 +++++++++++++++++++++++ live_examples/streams.py | 6 ++++++ 2 files changed, 29 insertions(+) create mode 100644 live_examples/stream.py diff --git a/live_examples/stream.py b/live_examples/stream.py new file mode 100644 index 0000000..9fbf014 --- /dev/null +++ b/live_examples/stream.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = "..." + +stream_name = "..." + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +stream = hub.get(stream_name) + +print(stream) + + diff --git a/live_examples/streams.py b/live_examples/streams.py index 293dfdc..54ff021 100644 --- a/live_examples/streams.py +++ b/live_examples/streams.py @@ -14,6 +14,12 @@ hub = Hub(mac, hub_name) +liveonly = False + +prefix = "" + +limit = 100 + resp = hub.list() print(resp.status_code) From 7587e463ae8f11531e28ae6c6b70df5aa08696a2 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 14:46:35 +0800 Subject: [PATCH 10/37] add live stream and streams --- live_examples/live_stream.py | 27 +++++++++++++++++++++++++++ live_examples/live_streams.py | 25 +++++++++++++++++++++++++ pili/hub.py | 6 ++++-- pili/stream.py | 8 +++++--- 4 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 live_examples/live_stream.py create mode 100644 live_examples/live_streams.py diff --git a/live_examples/live_stream.py b/live_examples/live_stream.py new file mode 100644 index 0000000..2a200c2 --- /dev/null +++ b/live_examples/live_stream.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "Y93_QIW2j-Bw84R7M07Mnno0re7TcEFq1InWpc9J" + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "BVclqX13x3uhr099JXcrfZS__wyF2fUnBFW4Kj5G" + +hub_name = 'berniezhibo' + +stream_name = "123" + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +stream = hub.get(stream_name) + +resp = stream.status() + +print(resp.status_code) +print(resp.headers) +print(resp.text) + + diff --git a/live_examples/live_streams.py b/live_examples/live_streams.py new file mode 100644 index 0000000..7644929 --- /dev/null +++ b/live_examples/live_streams.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "Y93_QIW2j-Bw84R7M07Mnno0re7TcEFq1InWpc9J" + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "BVclqX13x3uhr099JXcrfZS__wyF2fUnBFW4Kj5G" + +hub_name = 'berniezhibo' + +stream_lists = ["123", "abc"] + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.batch_live_status(stream_lists) + +print(resp.status_code) +print(resp.headers) +print(resp.text) + + diff --git a/pili/hub.py b/pili/hub.py index 7a7f278..0ef9f79 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -56,8 +56,10 @@ def list(self, **kwargs): data: 正整数,数据帧率 """ def batch_live_status(self, streams): - res = api.batch_live_status(self.__auth__, hub=self.__hub__, streams=streams) - return res["items"] + encoded = json.dumps({"items": streams}) + url = "http://%s/%s/hubs/%s/livestreams?" % (API_HOST, API_VERSION, self.__hub__) + return api._post(url=url, auth=self.__auth__, data=encoded) + def bandwidth_count_now(self): url = "http://%s/%s/hubs/%s/stat/play" % (API_HOST, API_VERSION, self.__hub__) diff --git a/pili/stream.py b/pili/stream.py index d0a262f..036353c 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -73,8 +73,9 @@ def enable(self): data: 正整数,数据帧率 """ def status(self): - res = api.get_status(self.__auth__, hub=self.hub, key=self.key) - return res + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s/live" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + return api._get(url=url, auth=self.__auth__) """ history 查询直播历史 @@ -114,10 +115,11 @@ def save_as(self, start_second=None, end_second=None, **kwargs): persistentID: 异步模式时,持久化异步处理任务ID,通常用不到该字段 """ def saveas(self, **kwargs): - key = urlsafe_b64encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] encoded_data = normalize_data(kwargs, keyword) + key = urlsafe_b64encode(self.key) return api._post(url, self.__auth__, data=encoded_data) From 9e11457c7377401889a5bab104d3edca2d709a28 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 17:04:05 +0800 Subject: [PATCH 11/37] disable --- live_examples/stream_disable.py | 26 ++++++++++++++++++++++++++ pili/stream.py | 7 ++++--- 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 live_examples/stream_disable.py diff --git a/live_examples/stream_disable.py b/live_examples/stream_disable.py new file mode 100644 index 0000000..e7d78f0 --- /dev/null +++ b/live_examples/stream_disable.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +stream_name = "..." + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +stream = hub.get(stream_name) + +# 不填参数或till为0表示不禁播,-1表示永久禁播,其他数字表示禁播到某一时刻的时间戳 +stream.disable(till=1521710848) + +print(stream) + + diff --git a/pili/stream.py b/pili/stream.py index 036353c..3352a1d 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -49,9 +49,10 @@ def refresh(self): # disable 禁用流,till Unix时间戳,在这之前流均不可用 def disable(self, till=None): - if till is None: - till = -1 - return api.disable_stream(self.__auth__, hub=self.hub, key=self.key, till=till) + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s/disabled" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + encoded = json.dumps({"disabledTill": till}) + return api._post(url=url, data=encoded, auth=self.__auth__) # disabled 判断流是否被禁用 def disabled(self): From 10a14afc73f6105b239c1a277353414e1bffd3c8 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 17:14:04 +0800 Subject: [PATCH 12/37] add snapshot --- live_examples/snapshot.py | 33 +++++++++++++++++++++++++++++++++ pili/stream.py | 24 ++++++++++++------------ 2 files changed, 45 insertions(+), 12 deletions(-) create mode 100644 live_examples/snapshot.py diff --git a/live_examples/snapshot.py b/live_examples/snapshot.py new file mode 100644 index 0000000..7ce365c --- /dev/null +++ b/live_examples/snapshot.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- + +""" +https://developer.qiniu.com/pili/api/2520/save-the-live-capture +""" + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = 'berniezhibo' + +stream_name = "..." + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +stream = hub.get(stream_name) + +# 不填参数或till为0表示不禁播,-1表示永久禁播,其他数字表示禁播到某一时刻的时间戳 +resp = stream.snapshot(time=1521710848, fname="123.jpg", format="jpg") + +print(resp.status_code) +print(resp.headers) +print(resp.text) + + + diff --git a/pili/stream.py b/pili/stream.py index 3352a1d..ff02a93 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -4,7 +4,7 @@ import time from base64 import urlsafe_b64encode import pili.api as api -import conf +from conf import API_HOST, API_VERSION from utils import normalize_path, normalize_data @@ -38,7 +38,7 @@ def __repr__(self): # refresh 主动更新流信息,会产生一次rpc调用 def refresh(self): key = urlsafe_b64encode(self.key) - url = "http://%s/%s/hubs/%s/streams/%s" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + url = "http://%s/%s/hubs/%s/streams/%s" % (API_HOST, API_VERSION, self.hub, key) data = api._get(url=url, auth=self.__auth__) self.__data__ = {} for p in ["disabledTill", "converts"]: @@ -50,7 +50,7 @@ def refresh(self): # disable 禁用流,till Unix时间戳,在这之前流均不可用 def disable(self, till=None): key = urlsafe_b64encode(self.key) - url = "http://%s/%s/hubs/%s/streams/%s/disabled" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + url = "http://%s/%s/hubs/%s/streams/%s/disabled" % (API_HOST, API_VERSION, self.hub, key) encoded = json.dumps({"disabledTill": till}) return api._post(url=url, data=encoded, auth=self.__auth__) @@ -75,7 +75,7 @@ def enable(self): """ def status(self): key = urlsafe_b64encode(self.key) - url = "http://%s/%s/hubs/%s/streams/%s/live" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + url = "http://%s/%s/hubs/%s/streams/%s/live" % (API_HOST, API_VERSION, self.hub, key) return api._get(url=url, auth=self.__auth__) """ @@ -90,7 +90,7 @@ def status(self): def history(self, **kwargs): key = urlsafe_b64encode(self.key) keyword = ['start', 'end'] - url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(conf.API_HOST, conf.API_VERSION, self.hub, key) + url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(API_HOST, API_VERSION, self.hub, key) url = normalize_path(kwargs, keyword, url) return api._get(url, self.__auth__) @@ -116,14 +116,13 @@ def save_as(self, start_second=None, end_second=None, **kwargs): persistentID: 异步模式时,持久化异步处理任务ID,通常用不到该字段 """ def saveas(self, **kwargs): - url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (API_HOST, API_VERSION, self.hub, self.key) keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] encoded_data = normalize_data(kwargs, keyword) key = urlsafe_b64encode(self.key) return api._post(url, self.__auth__, data=encoded_data) - """ snapshot 保存直播截图到存储空间 输入参数: @@ -134,10 +133,11 @@ def saveas(self, **kwargs): fname: 保存到存储空间的文件名 """ def snapshot(self, **kwargs): - kwargs["hub"] = self.hub - kwargs["key"] = self.key - res = api.stream_snapshot(self.__auth__, **kwargs) - return res + keyword = ['time', 'fname', 'format'] + encoded_data = normalize_data(kwargs, keyword) + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s/snapshot" % (API_HOST, API_VERSION, self.hub, key) + return api._post(url, self.__auth__, data=encoded_data) """ update_converts 更改流的转码规格 @@ -147,7 +147,7 @@ def snapshot(self, **kwargs): """ def update_converts(self, profiles=[]): key = urlsafe_b64encode(self.key) - url = "http://%s/%s/hubs/%s/streams/%s/converts" % (conf.API_HOST, conf.API_VERSION, self.hub, key) + url = "http://%s/%s/hubs/%s/streams/%s/converts" % (API_HOST, API_VERSION, self.hub, key) encoded_data = json.dumps({"converts": profiles}) return api._post(url, self.__auth__, data=encoded_data) From e9ad23de5d2df4c6291ffc81759784bf4a196980 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 17:15:15 +0800 Subject: [PATCH 13/37] fix snapshot --- live_examples/snapshot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/live_examples/snapshot.py b/live_examples/snapshot.py index 7ce365c..7cd5a23 100644 --- a/live_examples/snapshot.py +++ b/live_examples/snapshot.py @@ -12,7 +12,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = 'berniezhibo' +hub_name = '...' stream_name = "..." From 5208d7ebb997515b055fb0be8b97e6324bdaaa62 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 22 Mar 2018 17:16:30 +0800 Subject: [PATCH 14/37] forget aksk --- live_examples/live_stream.py | 6 +++--- live_examples/live_streams.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/live_examples/live_stream.py b/live_examples/live_stream.py index 2a200c2..c626a5c 100644 --- a/live_examples/live_stream.py +++ b/live_examples/live_stream.py @@ -3,12 +3,12 @@ from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey -access_key = "Y93_QIW2j-Bw84R7M07Mnno0re7TcEFq1InWpc9J" +access_key = "..." # 替换成自己 Qiniu 账号的 SecretKey -secret_key = "BVclqX13x3uhr099JXcrfZS__wyF2fUnBFW4Kj5G" +secret_key = "..." -hub_name = 'berniezhibo' +hub_name = '...' stream_name = "123" diff --git a/live_examples/live_streams.py b/live_examples/live_streams.py index 7644929..da9a057 100644 --- a/live_examples/live_streams.py +++ b/live_examples/live_streams.py @@ -3,12 +3,12 @@ from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey -access_key = "Y93_QIW2j-Bw84R7M07Mnno0re7TcEFq1InWpc9J" +access_key = "..." # 替换成自己 Qiniu 账号的 SecretKey -secret_key = "BVclqX13x3uhr099JXcrfZS__wyF2fUnBFW4Kj5G" +secret_key = "..." -hub_name = 'berniezhibo' +hub_name = '...' stream_lists = ["123", "abc"] From ceb810bbde2b0064014e5e4685554156b7e79c43 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 23 Mar 2018 17:09:08 +0800 Subject: [PATCH 15/37] delete surplus api add test batch and create --- pili/api.py | 134 ++++--------------------------------------- tests/test_hub.py | 31 ++++++---- tests/test_stream.py | 14 ++--- 3 files changed, 39 insertions(+), 140 deletions(-) diff --git a/pili/api.py b/pili/api.py index f479164..b4a7c4f 100644 --- a/pili/api.py +++ b/pili/api.py @@ -4,18 +4,18 @@ import requests import json import base64 -from compat import urlparse - - -def normalize(args, keyword): - if set(args) - set(keyword): - raise ValueError('invalid key') - for k, v in args.items(): - if v is None: - del args[k] - return args - - +# from compat import urlparse +# +# +# def normalize(args, keyword): +# if set(args) - set(keyword): +# raise ValueError('invalid key') +# for k, v in args.items(): +# if v is None: +# del args[k] +# return args +# +# @auth_interface def delete_room(version, roomName): url = "http://%s/%s/rooms/%s" % (conf.RTC_API_HOST, version, roomName) @@ -56,116 +56,6 @@ def create_room(ownerId, version, roomName=None): return req -@auth_interface -def create_stream(hub, **kwargs): - keyword = ['key'] - encoded = json.dumps(normalize(kwargs, keyword)) - url = "http://%s/%s/hubs/%s/streams" % (conf.API_HOST, conf.API_VERSION, hub) - return Request(url=url, data=encoded) - - -@auth_interface -def get_stream(hub, key): - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s" % (conf.API_HOST, conf.API_VERSION, hub, key) - return Request(url=url) - - -@auth_interface -def get_stream_list(hub, **kwargs): - keyword = ['liveonly', 'prefix', 'limit', 'marker'] - args = normalize(kwargs, keyword) - url = "http://%s/%s/hubs/%s/streams?" % (conf.API_HOST, conf.API_VERSION, hub) - for k, v in args.items(): - url += "&%s=%s" % (k, v) - return Request(url=url) - - -@auth_interface -def batch_live_status(hub, streams): - encoded = json.dumps({"items": streams}) - url = "http://%s/%s/hubs/%s/livestreams?" % (conf.API_HOST, conf.API_VERSION, hub) - return Request(url=url, data=encoded) - - -@auth_interface -def disable_stream(hub, key, till): - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s/disabled" % (conf.API_HOST, conf.API_VERSION, hub, key) - encoded = json.dumps({"disabledTill": till}) - return Request(url=url, data=encoded) - - -@auth_interface -def get_status(hub, key): - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s/live" % (conf.API_HOST, conf.API_VERSION, hub, key) - return Request(url=url) - - -@auth_interface -def stream_saveas(hub, key, **kwargs): - keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] - encoded = json.dumps(normalize(kwargs, keyword)) - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (conf.API_HOST, conf.API_VERSION, hub, key) - return Request(url=url, data=encoded) - - -@auth_interface -def stream_snapshot(hub, key, **kwargs): - keyword = ['time', 'fname', 'format'] - encoded = json.dumps(normalize(kwargs, keyword)) - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s/snapshot" % (conf.API_HOST, conf.API_VERSION, hub, key) - return Request(url=url, data=encoded) - - - -@auth_interface -def get_history(hub, key, **kwargs): - keyword = ['start', 'end'] - args = normalize(kwargs, keyword) - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s/historyactivity?" % (conf.API_HOST, conf.API_VERSION, hub, key) - for k, v in args.items(): - url += "&%s=%s" % (k, v) - r = Request(url=url) - print r.url - - # return requests.get(url=url) - - -@auth_interface -def update_stream_converts(hub, key, profiles): - key = base64.urlsafe_b64encode(key) - url = "http://%s/%s/hubs/%s/streams/%s/converts" % (conf.API_HOST, conf.API_VERSION, hub, key) - encoded = json.dumps({"converts": profiles}) - return Request(url=url, data=encoded) - - -@auth_interface -def bandwidth_count_now(hub): - url = "http://%s/%s/hubs/%s/stat/play" % (conf.API_HOST, conf.API_VERSION, hub) - return Request(url=url) - - -@auth_interface -def bandwidth_count_history(hub, **kwargs): - keyword = ['start', 'end', 'limit', 'marker'] - args = normalize(kwargs, keyword) - url = "http://%s/%s/hubs/%s/stat/play/history?" % (conf.API_HOST, conf.API_VERSION, hub) - for k, v in args.items(): - url += "&%s=%s" % (k, v) - return Request(url=url) - - -@auth_interface -def bandwidth_count_detail(hub, time): - url = "http://%s/%s/hubs/%s/stat/play/history/detail?time=%s" % (conf.API_HOST, conf.API_VERSION, hub, time) - return Request(url=url) - - def _get(url, auth): print("get") hearders = auth.authed("GET", url) diff --git a/tests/test_hub.py b/tests/test_hub.py index 3e99f5d..a906fd9 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -2,8 +2,12 @@ import os import unittest +import time +import random +import json -import pili +from pili import Hub, Mac +from pili.conf import API_HOST def env(key): @@ -16,20 +20,25 @@ def env(key): class TestHubCases(unittest.TestCase): def setUp(self): - hub_name = "PiliSDKTest" - access_key = env("QINIU_ACCESS_KEY") - secret_key = env("QINIU_SECRET_KEY") + hub_name = env("TEST_HUB") + access_key = env("access_key") + secret_key = env("secret_key") + if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") if env("PILI_API_HOST") != "": - pili.conf.API_HOST = env("PILI_API_HOST") - client = pili.Client(pili.Mac(access_key, secret_key)) - self.hub = client.hub(hub_name) + API_HOST = env("PILI_API_HOST") + mac = Mac(access_key, secret_key) + self.hub = Hub(mac, hub_name) # 这个测试case需要保持推流test1 def test_batch_live_status(self): items = self.hub.batch_live_status(["test1", "test2"]) - self.assertEqual(len(items), 1) - self.assertEqual(items[0]["key"], "test1") - self.assertTrue(items[0]["startAt"] > 0) - self.assertTrue(items[0]["bps"] > 0) + self.assertEqual(items.status_code, 200) + self.assertIn("test1", json.loads(items.text).get("items")[0].get("key")) + + def test_create_strean(self): + items = self.hub.create(key="streamtest" + str(int(random.random()*1e10))+str(time.time())[:10]) + self.assertEqual(items.status_code, 200) + self.assertEqual({}, json.loads(items.text)) + diff --git a/tests/test_stream.py b/tests/test_stream.py index 8afc674..5531e42 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -5,7 +5,7 @@ import time import unittest -import pili +from pili import Mac, Hub def env(key): @@ -24,18 +24,18 @@ def setUp(self): if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") if env("PILI_API_HOST") != "": - pili.conf.API_HOST = env("PILI_API_HOST") - client = pili.Client(pili.Mac(access_key, secret_key)) - self.hub = client.hub(hub_name) + API_HOST = env("PILI_API_HOST") + mac = Mac(access_key, secret_key) + self.hub = Hub(mac, hub_name) self.stream_title = "streamTest" + str(int(random.random()*1e10)) def test_stream_create(self): - stream = self.hub.create(self.stream_title) + stream = self.hub.create(key=self.stream_title) self.assertEqual(stream.hub, "PiliSDKTest") self.assertEqual(stream.key, self.stream_title) def test_stream_disable(self): - stream = self.hub.create(self.stream_title) + stream = self.hub.create(key=self.stream_title) self.assertFalse(stream.disabled()) stream.disable() stream = stream.refresh() @@ -48,7 +48,7 @@ def test_stream_disable(self): self.assertFalse(stream.disabled()) def test_stream_converts(self): - stream = self.hub.create(self.stream_title) + stream = self.hub.create(key=self.stream_title) self.assertEqual(len(stream.converts), 0) stream.update_converts(["480p", "720p"]) stream = stream.refresh() From b854caa547afa877454a2b71294b0f50cfa9be4b Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 23 Mar 2018 17:40:04 +0800 Subject: [PATCH 16/37] fix refresh and test disable --- pili/stream.py | 14 +++----------- tests/test_hub.py | 8 ++++++-- tests/test_stream.py | 15 +++++---------- 3 files changed, 14 insertions(+), 23 deletions(-) diff --git a/pili/stream.py b/pili/stream.py index ff02a93..be28ce9 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -41,11 +41,11 @@ def refresh(self): url = "http://%s/%s/hubs/%s/streams/%s" % (API_HOST, API_VERSION, self.hub, key) data = api._get(url=url, auth=self.__auth__) self.__data__ = {} - for p in ["disabledTill", "converts"]: - self.__data__[p] = data[p] if p in data else None + for p in ["disabledTill", "converts", "createdAt", "updatedAt", "expireAt", "watermark", "converts"]: + self.__data__[p] = json.loads(data.text).get(p) if p in data.text else None self.__data__["key"] = self.key self.__data__["hub"] = self.hub - return self + return self.__data__ # disable 禁用流,till Unix时间戳,在这之前流均不可用 def disable(self, till=None): @@ -54,14 +54,6 @@ def disable(self, till=None): encoded = json.dumps({"disabledTill": till}) return api._post(url=url, data=encoded, auth=self.__auth__) - # disabled 判断流是否被禁用 - def disabled(self): - return self.disabledTill == -1 or self.disabledTill > int(time.time()) - - # enable 开启流 - def enable(self): - return api.disable_stream(self.__auth__, hub=self.hub, key=self.key, till=0) - """ status 查询直播信息 返回值: diff --git a/tests/test_hub.py b/tests/test_hub.py index a906fd9..1ecdd11 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -37,8 +37,12 @@ def test_batch_live_status(self): self.assertEqual(items.status_code, 200) self.assertIn("test1", json.loads(items.text).get("items")[0].get("key")) - def test_create_strean(self): - items = self.hub.create(key="streamtest" + str(int(random.random()*1e10))+str(time.time())[:10]) + def test_create_stream(self): + self.stream_key = "streamtest" + str(int(random.random()*1e10))+str(time.time())[:10] + items = self.hub.create(key=self.stream_key) self.assertEqual(items.status_code, 200) self.assertEqual({}, json.loads(items.text)) + def test_query_streams(self): + items = self.hub.get("test1") + self.assertNotEqual(None, items) diff --git a/tests/test_stream.py b/tests/test_stream.py index 5531e42..59816cb 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -4,6 +4,7 @@ import random import time import unittest +import json from pili import Mac, Hub @@ -36,16 +37,10 @@ def test_stream_create(self): def test_stream_disable(self): stream = self.hub.create(key=self.stream_title) - self.assertFalse(stream.disabled()) - stream.disable() - stream = stream.refresh() - self.assertTrue(stream.disabled()) - stream.disable(int(time.time()) + 1) - stream = stream.refresh() - self.assertTrue(stream.disabled()) - time.sleep(2) - stream = stream.refresh() - self.assertFalse(stream.disabled()) + self.assertEqual({}, json.loads(stream.disable(-1).text)) + self.assertEqual(-1, stream.refresh().get("disabledTill")) + stream.disable(0) + self.assertEqual(0, stream.refresh().get("disabledTill")) def test_stream_converts(self): stream = self.hub.create(key=self.stream_title) From 7dde48af5451d089bb7c9ccd73733a517fdacd98 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Sun, 25 Mar 2018 18:55:03 +0800 Subject: [PATCH 17/37] add stream test --- tests/test_stream.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/tests/test_stream.py b/tests/test_stream.py index 59816cb..37ad102 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -19,9 +19,9 @@ def env(key): class TestStreamCases(unittest.TestCase): def setUp(self): - hub_name = "PiliSDKTest" - access_key = env("QINIU_ACCESS_KEY") - secret_key = env("QINIU_SECRET_KEY") + hub_name = env("TEST_HUB") + access_key = env("access_key") + secret_key = env("secret_key") if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") if env("PILI_API_HOST") != "": @@ -70,16 +70,10 @@ def test_stream_saveas(self): # 这个测试需要维持推流test1 def test_stream_snashot(self): stream = self.hub.get("test1") - ret = stream.snapshot() - self.assertTrue(ret["fname"]) ret = stream.snapshot(fname="test1.jpg") - self.assertEqual(ret["fname"], "test1.jpg") + self.assertEqual(json.loads(ret.text)["fname"], "test1.jpg") # 这个测试需要维持推流test1 def test_stream_history(self): stream = self.hub.get("test1") - now = int(time.time()) - ret = stream.history(now - 86400, now) - self.assertTrue(len(ret) > 0) - self.assertTrue(ret[0]["start"] > 0) - self.assertTrue(ret[0]["end"] > 0) + self.assertEqual(200, stream.history().status_code) From 43148bf20b454c1e4aa50ec3ab662754f1f4c602 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 28 Mar 2018 14:49:03 +0800 Subject: [PATCH 18/37] fix save_as --- pili/stream.py | 9 ++++----- tests/test_stream.py | 14 ++++++++++---- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/pili/stream.py b/pili/stream.py index be28ce9..8e420da 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -87,8 +87,8 @@ def history(self, **kwargs): return api._get(url, self.__auth__) # save_as等同于saveas接口,出于兼容考虑,暂时保留 - def save_as(self, start_second=None, end_second=None, **kwargs): - return self.saveas(start_second, end_second, **kwargs) + def save_as(self, **kwargs): + return self.saveas(**kwargs) """ saveas 保存直播回放到存储空间 @@ -108,11 +108,10 @@ def save_as(self, start_second=None, end_second=None, **kwargs): persistentID: 异步模式时,持久化异步处理任务ID,通常用不到该字段 """ def saveas(self, **kwargs): - url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (API_HOST, API_VERSION, self.hub, self.key) - + key = urlsafe_b64encode(self.key) + url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (API_HOST, API_VERSION, self.hub, key) keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] encoded_data = normalize_data(kwargs, keyword) - key = urlsafe_b64encode(self.key) return api._post(url, self.__auth__, data=encoded_data) """ diff --git a/tests/test_stream.py b/tests/test_stream.py index 37ad102..30c13e5 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -55,11 +55,16 @@ def test_stream_converts(self): # 这个测试需要维持推流test1 def test_stream_saveas(self): stream = self.hub.get("test1") - stream.save_as() + ret = stream.save_as() + self.assertEqual(200, ret.status_code) now = int(time.time()) - stream.save_as(now - 20) - stream.save_as(now - 20, now) - ret = stream.save_as(now - 20, now, fname="test1.mp4", format="mp4") + ret = stream.saveas(start=now - 20) + self.assertIn(ret.status_code, (200, 619)) + ret = stream.save_as(start=now - 20, end=now) + self.assertIn(ret.status_code, (200, 619)) + ret = stream.saveas(start=now - 20, end=now, fname="test1.m3u8", format="m3u8") + self.assertEqual("test1.m3u8", json.loads(ret.text).get("fname")) + ret = stream.save_as(start=now - 20, end=now, fname="test1.mp4", format="mp4") self.assertEqual(ret["fname"], "test1.mp4") self.assertTrue(ret["persistentID"]) try: @@ -77,3 +82,4 @@ def test_stream_snashot(self): def test_stream_history(self): stream = self.hub.get("test1") self.assertEqual(200, stream.history().status_code) + From 0225b033cb27bda0e5f3793cbb4aa8890c580488 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 28 Mar 2018 16:21:49 +0800 Subject: [PATCH 19/37] delete room --- interact_micro_example/create_room.py | 4 ++-- interact_micro_example/delete_room.py | 2 +- pili/api.py | 4 ++++ pili/roomClient.py | 18 +++++++++++++----- pili/stream.py | 9 ++++----- 5 files changed, 24 insertions(+), 13 deletions(-) diff --git a/interact_micro_example/create_room.py b/interact_micro_example/create_room.py index 2050e39..403bf57 100644 --- a/interact_micro_example/create_room.py +++ b/interact_micro_example/create_room.py @@ -13,6 +13,6 @@ room = RoomClient(mac) -print room.createRoom('admin_user', 'roomname') +print(room.create_room('admin_user', 'roomname')) -# print room.roomToken('roomname', 'admin_user', 'admin', 36000) +# print(room.roomToken('roomname', 'admin_user', 'admin', 36000)) diff --git a/interact_micro_example/delete_room.py b/interact_micro_example/delete_room.py index 61313a0..4c4f6aa 100644 --- a/interact_micro_example/delete_room.py +++ b/interact_micro_example/delete_room.py @@ -12,4 +12,4 @@ room = RoomClient(mac) -print room.deleteRoom('roomname') +print(room.deleteRoom('roomname')) diff --git a/pili/api.py b/pili/api.py index b4a7c4f..9ef1d21 100644 --- a/pili/api.py +++ b/pili/api.py @@ -67,3 +67,7 @@ def _post(url, auth, data): hearders = auth.authed("POST", url, body=data) return requests.post(url=url, headers=hearders, data=data) +def _delete(url, auth): + print("delete") + hearders = auth.authed("DELETE", url) + return requests.delete(url=url, headers=hearders) \ No newline at end of file diff --git a/pili/roomClient.py b/pili/roomClient.py index 99db8ec..82ec6be 100755 --- a/pili/roomClient.py +++ b/pili/roomClient.py @@ -5,6 +5,8 @@ import pili.api as api from utils import urlsafe_base64_encode +from conf import RTC_API_HOST + class RoomClient(object): """docstring for RoomClient""" @@ -12,17 +14,23 @@ def __init__(self, credentials): self.__credentials__ = credentials self.__auth__ = credentials.__auth__ - def createRoom(self, ownerId, roomName=None, version='v2'): - res = api.create_room(self.__auth__, ownerId=ownerId, roomName=roomName, version=version) - return res + def create_room(self, ownerId, roomName=None, version='v2'): + params = {'owner_id': ownerId} + url = "http://%s/%s/rooms" % (RTC_API_HOST, version) + if bool(roomName): + params['room_name'] = roomName + encoded = json.dumps(params) + return api._post(url=url, auth=self.__auth__, data=encoded) def getRoom(self, roomName, version='v2'): res = api.get_room(self.__auth__, roomName=roomName, version=version) return res def deleteRoom(self, roomName, version='v2'): - res = api.delete_room(self.__auth__, roomName=roomName, version=version) - return res + url = "http://%s/%s/rooms/%s" % (RTC_API_HOST, version, roomName) + return api._delete(url=url, auth=self.__auth__) + + def getUser(self, roomName, version='v2'): res = api.get_user(self.__auth__, roomName=roomName, version=version) diff --git a/pili/stream.py b/pili/stream.py index 8e420da..be1c200 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -84,7 +84,7 @@ def history(self, **kwargs): keyword = ['start', 'end'] url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(API_HOST, API_VERSION, self.hub, key) url = normalize_path(kwargs, keyword, url) - return api._get(url, self.__auth__) + return api._get(url=url, auth=self.__auth__) # save_as等同于saveas接口,出于兼容考虑,暂时保留 def save_as(self, **kwargs): @@ -112,7 +112,7 @@ def saveas(self, **kwargs): url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (API_HOST, API_VERSION, self.hub, key) keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] encoded_data = normalize_data(kwargs, keyword) - return api._post(url, self.__auth__, data=encoded_data) + return api._post(url=url, auth=self.__auth__, data=encoded_data) """ snapshot 保存直播截图到存储空间 @@ -128,7 +128,7 @@ def snapshot(self, **kwargs): encoded_data = normalize_data(kwargs, keyword) key = urlsafe_b64encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/snapshot" % (API_HOST, API_VERSION, self.hub, key) - return api._post(url, self.__auth__, data=encoded_data) + return api._post(url=url, auth=self.__auth__, data=encoded_data) """ update_converts 更改流的转码规格 @@ -140,8 +140,7 @@ def update_converts(self, profiles=[]): key = urlsafe_b64encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/converts" % (API_HOST, API_VERSION, self.hub, key) encoded_data = json.dumps({"converts": profiles}) - return api._post(url, self.__auth__, data=encoded_data) - + return api._post(url=url, auth=self.__auth__, data=encoded_data) def to_json(self): return json.dumps(self.data) From 5140f0929bb84be39db1fdb498c3f156da2bb13a Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 28 Mar 2018 16:31:34 +0800 Subject: [PATCH 20/37] add kick,query --- interact_micro_example/kick_user.py | 2 +- interact_micro_example/query_room.py | 2 +- interact_micro_example/query_user.py | 2 +- pili/roomClient.py | 14 ++++++-------- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/interact_micro_example/kick_user.py b/interact_micro_example/kick_user.py index d452573..16416a1 100644 --- a/interact_micro_example/kick_user.py +++ b/interact_micro_example/kick_user.py @@ -12,4 +12,4 @@ room = RoomClient(mac) -print room.kickUser('roomname', 'admin_user') +print(room.kickUser('roomname', 'admin_user')) diff --git a/interact_micro_example/query_room.py b/interact_micro_example/query_room.py index 8b9be60..4a53175 100644 --- a/interact_micro_example/query_room.py +++ b/interact_micro_example/query_room.py @@ -12,4 +12,4 @@ room = RoomClient(mac) -print room.getRoom('roomname') +print(room.getRoom('roomname')) diff --git a/interact_micro_example/query_user.py b/interact_micro_example/query_user.py index c80b912..6b9f4b9 100644 --- a/interact_micro_example/query_user.py +++ b/interact_micro_example/query_user.py @@ -12,4 +12,4 @@ room = RoomClient(mac) -print room.getUser('roomname') +print(room.getUser('roomname')) diff --git a/pili/roomClient.py b/pili/roomClient.py index 82ec6be..5b42de5 100755 --- a/pili/roomClient.py +++ b/pili/roomClient.py @@ -23,22 +23,20 @@ def create_room(self, ownerId, roomName=None, version='v2'): return api._post(url=url, auth=self.__auth__, data=encoded) def getRoom(self, roomName, version='v2'): - res = api.get_room(self.__auth__, roomName=roomName, version=version) - return res + url = "http://%s/%s/rooms/%s" % (RTC_API_HOST, version, roomName) + return api._get(url=url, auth=self.__auth__) def deleteRoom(self, roomName, version='v2'): url = "http://%s/%s/rooms/%s" % (RTC_API_HOST, version, roomName) return api._delete(url=url, auth=self.__auth__) - - def getUser(self, roomName, version='v2'): - res = api.get_user(self.__auth__, roomName=roomName, version=version) - return res + url = "http://%s/%s/rooms/%s/users" % (RTC_API_HOST, version, roomName) + return api._get(url=url, auth=self.__auth__) def kickUser(self, roomName, userId, version='v2'): - res = api.kick_user(self.__auth__, roomName=roomName, userId=userId, version=version) - return res + url = "http://%s/%s/rooms/%s/users/%s" % (RTC_API_HOST, version, roomName, userId) + return api._delete(url=url, auth=self.__auth__) def roomToken(self, roomName, userId, perm, expireAt, version='v2'): if version == 'v2': From 028c1ee126bf6438392daf1f05b72cb5f69f44ae Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 28 Mar 2018 17:44:01 +0800 Subject: [PATCH 21/37] arrange dir --- interact_micro_example/create_room.py | 2 - interact_micro_example/create_token.py | 15 +++++ operations_example/bandwidth_count_detail.py | 21 ++++++ operations_example/bandwidth_count_history.py | 21 ++++++ .../bandwith_count_now.py | 6 +- pili/api.py | 64 ++----------------- 6 files changed, 63 insertions(+), 66 deletions(-) create mode 100644 interact_micro_example/create_token.py create mode 100644 operations_example/bandwidth_count_detail.py create mode 100644 operations_example/bandwidth_count_history.py rename live_examples/bandwidth_count.py => operations_example/bandwith_count_now.py (64%) diff --git a/interact_micro_example/create_room.py b/interact_micro_example/create_room.py index 403bf57..f8759d0 100644 --- a/interact_micro_example/create_room.py +++ b/interact_micro_example/create_room.py @@ -8,11 +8,9 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." - mac = Mac(access_key, secret_key) room = RoomClient(mac) print(room.create_room('admin_user', 'roomname')) -# print(room.roomToken('roomname', 'admin_user', 'admin', 36000)) diff --git a/interact_micro_example/create_token.py b/interact_micro_example/create_token.py new file mode 100644 index 0000000..4ccdbe4 --- /dev/null +++ b/interact_micro_example/create_token.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- + +from pili import RoomClient, Mac + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +mac = Mac(access_key, secret_key) + +room = RoomClient(mac) + +print(room.roomToken('roomname', 'admin_user', 'admin', 3600)) diff --git a/operations_example/bandwidth_count_detail.py b/operations_example/bandwidth_count_detail.py new file mode 100644 index 0000000..b0eb5d4 --- /dev/null +++ b/operations_example/bandwidth_count_detail.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import time +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.bandwidth_count_detail(int(time.time())) + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/operations_example/bandwidth_count_history.py b/operations_example/bandwidth_count_history.py new file mode 100644 index 0000000..2b9cf9a --- /dev/null +++ b/operations_example/bandwidth_count_history.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import time +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.bandwidth_count_history(start=int(time.time())-100, end=int(time.time()), limit=100, marker=None) + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/live_examples/bandwidth_count.py b/operations_example/bandwith_count_now.py similarity index 64% rename from live_examples/bandwidth_count.py rename to operations_example/bandwith_count_now.py index 795a9e8..70f285c 100644 --- a/live_examples/bandwidth_count.py +++ b/operations_example/bandwith_count_now.py @@ -14,11 +14,7 @@ hub = Hub(mac, hub_name) -# resp = hub.bandwidth_count_now() -# -# resp = hub.bandwidth_count_detail(1512616339) - -resp = hub.bandwidth_count_history(start=1512616339, end=1512616400, limit=100, marker=None) +resp = hub.bandwidth_count_now() print(resp.status_code) print(resp.headers) diff --git a/pili/api.py b/pili/api.py index 9ef1d21..2194656 100644 --- a/pili/api.py +++ b/pili/api.py @@ -1,73 +1,19 @@ -from .auth import auth_interface -import pili.conf as conf -from requests import Request -import requests -import json -import base64 -# from compat import urlparse -# -# -# def normalize(args, keyword): -# if set(args) - set(keyword): -# raise ValueError('invalid key') -# for k, v in args.items(): -# if v is None: -# del args[k] -# return args -# -# -@auth_interface -def delete_room(version, roomName): - url = "http://%s/%s/rooms/%s" % (conf.RTC_API_HOST, version, roomName) - req = Request(url=url) - req.get_method = lambda: 'DELETE' - return req - - -@auth_interface -def get_room(version, roomName): - url = "http://%s/%s/rooms/%s" % (conf.RTC_API_HOST, version, roomName) - return Request(url=url) - - -@auth_interface -def get_user(version, roomName): - url = "http://%s/%s/rooms/%s/users" % (conf.RTC_API_HOST, version, roomName) - return Request(url=url) - - -@auth_interface -def kick_user(version, roomName, userId): - url = "http://%s/%s/rooms/%s/users/%s" % (conf.RTC_API_HOST, version, roomName, userId) - req = Request(url=url) - req.get_method = lambda: 'DELETE' - return req - - -@auth_interface -def create_room(ownerId, version, roomName=None): - params = {'owner_id': ownerId} - url = "http://%s/%s/rooms" % (conf.RTC_API_HOST, version) - if bool(roomName): - params['room_name'] = roomName - encoded = json.dumps(params) - req = Request(url=url, data=encoded) - req.get_method = lambda: 'POST' - return req +from requests import get, post, delete def _get(url, auth): print("get") hearders = auth.authed("GET", url) - return requests.get(url=url, headers=hearders) + return get(url=url, headers=hearders) def _post(url, auth, data): print("post") hearders = auth.authed("POST", url, body=data) - return requests.post(url=url, headers=hearders, data=data) + return post(url=url, headers=hearders, data=data) + def _delete(url, auth): print("delete") hearders = auth.authed("DELETE", url) - return requests.delete(url=url, headers=hearders) \ No newline at end of file + return delete(url=url, headers=hearders) \ No newline at end of file From 30a2fbda3835d928e8812de8b75976eb2a3f0c3f Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 28 Mar 2018 18:11:37 +0800 Subject: [PATCH 22/37] add wm --- operations_example/wm_create.py | 22 ++++++++++++++++++++++ operations_example/wm_query.py | 21 +++++++++++++++++++++ pili/hub.py | 28 +++++++++++++++++++--------- 3 files changed, 62 insertions(+), 9 deletions(-) create mode 100644 operations_example/wm_create.py create mode 100644 operations_example/wm_query.py diff --git a/operations_example/wm_create.py b/operations_example/wm_create.py new file mode 100644 index 0000000..9da1ba2 --- /dev/null +++ b/operations_example/wm_create.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.wm_crete(name="test1", comment="for_test1", left='50%', + top='50%', width='10%', imageURL="http://xxx.xxx.com/abc.png") + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/operations_example/wm_query.py b/operations_example/wm_query.py new file mode 100644 index 0000000..711c1c0 --- /dev/null +++ b/operations_example/wm_query.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.wm_query(limit=100) + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/pili/hub.py b/pili/hub.py index 0ef9f79..0405853 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -6,6 +6,7 @@ from utils import normalize_path, normalize_data import json + class Hub(object): def __init__(self, mac, hub): self.__auth__ = mac.__auth__ @@ -14,11 +15,10 @@ def __init__(self, mac, hub): # create 创建一路流 def create(self, **kwargs): keyword = ['key'] - url = "http://%s/%s/hubs/%s/streams" % (API_HOST, API_VERSION, self.__hub__) + url = "http://{0}/{1}/hubs/{2}/streams".format(API_HOST, API_VERSION, self.__hub__) encoded = normalize_data(kwargs, keyword) return api._post(url=url, auth=self.__auth__, data=encoded) - # 获取一路流 def get(self, key): return Stream(self.__auth__, hub=self.__hub__, key=key) @@ -35,12 +35,11 @@ def get(self, key): marker: 这次遍历得到的游标,下次请求应该带上,如果为"",则表示已遍历完所有流 """ def list(self, **kwargs): - url = "http://%s/%s/hubs/%s/streams?" % (API_HOST, API_VERSION, self.__hub__) + url = "http://{0}/{1}/hubs/{2}/streams?".format(API_HOST, API_VERSION, self.__hub__) keyword = ['liveonly', 'prefix', 'limit', 'marker'] url = normalize_path(kwargs, keyword, url) return api._get(url=url, auth=self.__auth__) - """ batch_live_status 批量查询流的直播信息 输入参数: @@ -55,23 +54,34 @@ def list(self, **kwargs): video: 正整数,视频帧率 data: 正整数,数据帧率 """ + def batch_live_status(self, streams): encoded = json.dumps({"items": streams}) - url = "http://%s/%s/hubs/%s/livestreams?" % (API_HOST, API_VERSION, self.__hub__) + url = "http://{0}/{1}/hubs/{2}/livestreams".format(API_HOST, API_VERSION, self.__hub__) return api._post(url=url, auth=self.__auth__, data=encoded) - def bandwidth_count_now(self): - url = "http://%s/%s/hubs/%s/stat/play" % (API_HOST, API_VERSION, self.__hub__) + url = "http://{0}/{1}/hubs/{2}/stat/play".format(API_HOST, API_VERSION, self.__hub__) return api._get(url, self.__auth__) def bandwidth_count_history(self, **kwargs): - url = "http://%s/%s/hubs/%s/stat/play/history?" % (API_HOST, API_VERSION, self.__hub__) + url = "http://{0}/{1}/hubs/{2}/stat/play/history".format(API_HOST, API_VERSION, self.__hub__) keyword = ['start', 'end', 'limit', 'marker'] url = normalize_path(kwargs, keyword, url) return api._get(url=url, auth=self.__auth__) def bandwidth_count_detail(self, time): - url = "http://%s/%s/hubs/%s/stat/play/history/detail?time=%s" % (API_HOST, API_VERSION, self.__hub__, time) + url = "http://{0}/{1}/hubs/{2}/stat/play/history/detail?time=%s".format(API_HOST, API_VERSION, self.__hub__, time) return api._get(url, self.__auth__) + def wm_crete(self, **kwargs): + keyword = ['name', 'comment', "left", "top", "width", "imageURL"] + encoded = normalize_data(kwargs, keyword) + url = "http://{0}/{1}/hubs/{2}/watermarktemplate".format(API_HOST, API_VERSION, self.__hub__) + return api._post(url=url, auth=self.__auth__, data=encoded) + + def wm_query(self, **kwargs): + keyword = ['limit'] + url = "http://{0}/{1}/hubs/{2}/watermarktemplate".format(API_HOST, API_VERSION, self.__hub__) + url = normalize_path(kwargs, keyword, url) + return api._get(url=url, auth=self.__auth__) From 535169c311590d5cb12384ccbf4c6e535c425a77 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Wed, 28 Mar 2018 18:28:43 +0800 Subject: [PATCH 23/37] add wm query,list --- operations_example/wm_create.py | 10 ++++++++++ operations_example/wm_download.py | 21 +++++++++++++++++++++ operations_example/wm_list.py | 21 +++++++++++++++++++++ operations_example/wm_query.py | 2 +- pili/hub.py | 12 ++++++++++-- 5 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 operations_example/wm_download.py create mode 100644 operations_example/wm_list.py diff --git a/operations_example/wm_create.py b/operations_example/wm_create.py index 9da1ba2..8497803 100644 --- a/operations_example/wm_create.py +++ b/operations_example/wm_create.py @@ -1,5 +1,15 @@ # -*- coding: utf-8 -*- +""" +name: 模版名称, ^[A-Za-z0-9-_]{4,64}$ +comment: 模版描述 +left: 水印图片左上角距离视频图像左上角的水平位置占视频宽度的百分比,[0%, 100%) +top: 水印图片左上角距离视频图像左上角的垂直位置占视频 度的百分比,[0%, 100%) +width: 水印图片的宽度占视频宽度的百分比,高度会等比缩放。[0%, 100%), 与left之和不能超过100 +imageURL: 水印图片地址,仅支持PNG格式 +imageData: base64编码的图片原始数据,与imageURL二选一! +""" + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/operations_example/wm_download.py b/operations_example/wm_download.py new file mode 100644 index 0000000..e0b6189 --- /dev/null +++ b/operations_example/wm_download.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.wm_download(name="test1") + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/operations_example/wm_list.py b/operations_example/wm_list.py new file mode 100644 index 0000000..ad9dce7 --- /dev/null +++ b/operations_example/wm_list.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +from pili import Mac, Hub + +# 替换成自己 Qiniu 账号的 AccessKey +access_key = "..." + +# 替换成自己 Qiniu 账号的 SecretKey +secret_key = "..." + +hub_name = '...' + +mac = Mac(access_key, secret_key) + +hub = Hub(mac, hub_name) + +resp = hub.wm_list(limit=100) + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/operations_example/wm_query.py b/operations_example/wm_query.py index 711c1c0..d3ca77f 100644 --- a/operations_example/wm_query.py +++ b/operations_example/wm_query.py @@ -14,7 +14,7 @@ hub = Hub(mac, hub_name) -resp = hub.wm_query(limit=100) +resp = hub.wm_query(name="test1") print(resp.status_code) print(resp.headers) diff --git a/pili/hub.py b/pili/hub.py index 0405853..a91a189 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -75,13 +75,21 @@ def bandwidth_count_detail(self, time): return api._get(url, self.__auth__) def wm_crete(self, **kwargs): - keyword = ['name', 'comment', "left", "top", "width", "imageURL"] + keyword = ['name', 'comment', "left", "top", "width", "imageURL", "imageData"] encoded = normalize_data(kwargs, keyword) url = "http://{0}/{1}/hubs/{2}/watermarktemplate".format(API_HOST, API_VERSION, self.__hub__) return api._post(url=url, auth=self.__auth__, data=encoded) - def wm_query(self, **kwargs): + def wm_list(self, **kwargs): keyword = ['limit'] url = "http://{0}/{1}/hubs/{2}/watermarktemplate".format(API_HOST, API_VERSION, self.__hub__) url = normalize_path(kwargs, keyword, url) return api._get(url=url, auth=self.__auth__) + + def wm_download(self, name): + url = "http://{0}/{1}/hubs/{2}/watermarktemplate/{3}/image".format(API_HOST, API_VERSION, self.__hub__, name) + return api._get(url=url, auth=self.__auth__) + + def wm_query(self, name): + url = "http://{0}/{1}/hubs/{2}/watermarktemplate/{3}".format(API_HOST, API_VERSION, self.__hub__, name) + return api._get(url=url, auth=self.__auth__) From d1aacb2a1a7119a09c865535a22092821eb6a53b Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 15:41:25 +0800 Subject: [PATCH 24/37] add room test --- setup.py | 2 +- tests/test_room.py | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 tests/test_room.py diff --git a/setup.py b/setup.py index 35f0371..9f1ead7 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ setup( name='pili2', - version='2.1.0', + version='2.2.0', keywords=('pili', 'streaming', 'hls', 'rtmp'), description='Pili Streaming Cloud Server-Side Library For Python', license='MIT License', diff --git a/tests/test_room.py b/tests/test_room.py new file mode 100644 index 0000000..243ec61 --- /dev/null +++ b/tests/test_room.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- + +import os +import unittest +import json + +from pili import RoomClient, Mac + + + +def env(key): + if key in os.environ: + return os.environ[key] + else: + return "" + + +class TestRoomCases(unittest.TestCase): + + def setUp(self): + access_key = env("access_key") + secret_key = env("secret_key") + + if access_key == "" or secret_key == "": + raise unittest.SkipTest("need set access_key or secret_key") + mac = Mac(access_key, secret_key) + self.room = RoomClient(mac) + + def test_create_room(self): + items = self.room.create_room('admin_user', 'roomname') + self.assertEqual("roomname", json.loads(items.text).get("room_name")) + + def test_create_token(self): + test_token = self.room.roomToken('roomname', 'admin_user', 'admin', 3600) + import base64 + decode_token = json.loads(base64.decodestring(test_token.split(":")[2])) + self.assertIn("admin_user", decode_token.get("user_id")) + self.assertIn("2.0", decode_token.get("version")) + self.assertIn("roomname", decode_token.get("room_name")) + + def test_delete_room(self): + resp = self.room.deleteRoom("roomname") + self.assertEqual({}, json.loads(resp.text)) + + def test_query_room(self): + resp = self.room.getRoom("roomname") + decode_data = json.loads(resp.text) + self.assertEqual("roomname", decode_data.get("room_name")) + + def test_query_user(self): + resp = self.room.getUser(roomName="roomname") + decode_data = json.loads(resp.text) + self.assertIn("active_users", decode_data) + + From 78e3798678bc3767aad428d39becd3fdd6967cd8 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 16:29:39 +0800 Subject: [PATCH 25/37] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e7f31b..b2c60f9 100644 --- a/README.md +++ b/README.md @@ -17,13 +17,19 @@ - Stream - [x] 流信息: stream.refresh() - [x] 禁用流: stream.disable(till) - - [x] 启用流: stream.enable() - [x] 查询直播状态: stream.status() - [x] 保存直播回放: stream.saveas(start, end, options) - [x] 保存直播截图: stream.snapshot(options) - [x] 更改流的实时转码规格: stream.update_converts(profiles) - [x] 查询直播历史: stream.history(start, end) +- Room +    - [x] 创建房间: room.create_room(options) +    - [x] 生成token: room.roomToken(options) +    - [x] 删除房间: room.deleteRoom(roomName) +    - [x] 踢除用户: room.kickUser(roomName, userId) +    - [x] 查询房间: room.getRoom(roomName) +    - [x] 查询在线用户: room.getUser(roomName) ## Contents From 2d3686123c4882c7ae47cd5918353ceadeb70a63 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 16:47:12 +0800 Subject: [PATCH 26/37] add readme --- README.md | 15 ++++++++------- interact_micro_example/create_room.py | 6 +++++- interact_micro_example/delete_room.py | 6 +++++- interact_micro_example/kick_user.py | 9 ++++++++- interact_micro_example/query_room.py | 6 +++++- interact_micro_example/query_user.py | 6 +++++- pili/api.py | 3 --- 7 files changed, 36 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index b2c60f9..9c57160 100644 --- a/README.md +++ b/README.md @@ -23,13 +23,14 @@ - [x] 更改流的实时转码规格: stream.update_converts(profiles) - [x] 查询直播历史: stream.history(start, end) -- Room -    - [x] 创建房间: room.create_room(options) -    - [x] 生成token: room.roomToken(options) -    - [x] 删除房间: room.deleteRoom(roomName) -    - [x] 踢除用户: room.kickUser(roomName, userId) -    - [x] 查询房间: room.getRoom(roomName) -    - [x] 查询在线用户: room.getUser(roomName) +- Stream + - [x] 创建房间: room.create_room(options) + - [x] 生成token: room.roomToken(options) + - [x] 删除房间: room.deleteRoom(roomName) + - [x] 踢除用户: room.kickUser(roomName, userId) + - [x] 查询房间: room.getRoom(roomName) + - [x] 查询在线用户: room.getUser(roomName) + ## Contents diff --git a/interact_micro_example/create_room.py b/interact_micro_example/create_room.py index f8759d0..4bcbb20 100644 --- a/interact_micro_example/create_room.py +++ b/interact_micro_example/create_room.py @@ -12,5 +12,9 @@ room = RoomClient(mac) -print(room.create_room('admin_user', 'roomname')) +resp = room.create_room('admin_user', 'roomname') + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/interact_micro_example/delete_room.py b/interact_micro_example/delete_room.py index 4c4f6aa..40bf1aa 100644 --- a/interact_micro_example/delete_room.py +++ b/interact_micro_example/delete_room.py @@ -12,4 +12,8 @@ room = RoomClient(mac) -print(room.deleteRoom('roomname')) +resp = room.deleteRoom('roomname') + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/interact_micro_example/kick_user.py b/interact_micro_example/kick_user.py index 16416a1..634384f 100644 --- a/interact_micro_example/kick_user.py +++ b/interact_micro_example/kick_user.py @@ -12,4 +12,11 @@ room = RoomClient(mac) -print(room.kickUser('roomname', 'admin_user')) +resp = room.kickUser('roomname11111', 'admin_user') + +print(resp.status_code) +print(resp.headers) +print(resp.text) + + + diff --git a/interact_micro_example/query_room.py b/interact_micro_example/query_room.py index 4a53175..14cb6d8 100644 --- a/interact_micro_example/query_room.py +++ b/interact_micro_example/query_room.py @@ -12,4 +12,8 @@ room = RoomClient(mac) -print(room.getRoom('roomname')) +resp = room.getRoom('roomname') + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/interact_micro_example/query_user.py b/interact_micro_example/query_user.py index 6b9f4b9..8ef192b 100644 --- a/interact_micro_example/query_user.py +++ b/interact_micro_example/query_user.py @@ -12,4 +12,8 @@ room = RoomClient(mac) -print(room.getUser('roomname')) +resp = room.getUser('roomname11111') + +print(resp.status_code) +print(resp.headers) +print(resp.text) diff --git a/pili/api.py b/pili/api.py index 2194656..c278930 100644 --- a/pili/api.py +++ b/pili/api.py @@ -2,18 +2,15 @@ def _get(url, auth): - print("get") hearders = auth.authed("GET", url) return get(url=url, headers=hearders) def _post(url, auth, data): - print("post") hearders = auth.authed("POST", url, body=data) return post(url=url, headers=hearders, data=data) def _delete(url, auth): - print("delete") hearders = auth.authed("DELETE", url) return delete(url=url, headers=hearders) \ No newline at end of file From d916cf3b18001f3559db688ae4e4b137b6e67c23 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 17:14:35 +0800 Subject: [PATCH 27/37] Update README.md --- README.md | 107 ++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 88 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 9c57160..f85c0ca 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ - [x] 更改流的实时转码规格: stream.update_converts(profiles) - [x] 查询直播历史: stream.history(start, end) -- Stream +- Room - [x] 创建房间: room.create_room(options) - [x] 生成token: room.roomToken(options) - [x] 删除房间: room.deleteRoom(roomName) @@ -53,12 +53,19 @@ - [Stream](#stream) - [Get Stream info](#get-stream-info) - [Disable a Stream](#disable-a-stream) - - [Enable a Stream](#enable-a-stream) - [Get Stream live status](#get-stream-live-status) - [Save Stream live playback](#save-stream-live-playback) - [Save Stream snapshot](#save-stream-snapshot) - [Update Stream converts](#update-stream-converts) - [Get Stream history activity](#get-stream-history-activity) + - [Room](#stream) + - [Create Room](#create-room) + - [Create Token](#create-token) + - [Delete Room](#delete-room) + - [Kick User](#kick-user) + - [Query Room](#query-room) + - [Query User](#query-user) + ## Installation @@ -82,7 +89,6 @@ secret_key = "" # 替换成自己 Qiniu 账号的 SecretKey hub_name = "" # Hub 必须事先存在 mac = pili.Mac(AccessKey, SecretKey) -client = pili.Client(mac) # ... ``` @@ -134,8 +140,7 @@ print pili.snapshot_play_url("live-snapshot.test.com", hub_name, "streamtitle") ```python mac = pili.Mac(AccessKey, SecretKey) -client = pili.Client(mac) -hub = client.hub("PiliSDKTest") +hub = Hub(mac, hub_name) ``` #### Create a new Stream @@ -205,19 +210,6 @@ print "after sleep 5 seconds:", stream.refresh(), stream.disabled() # after sleep 5 seconds: {"disabledTill": 1488378022, "converts": [], "hub": "PiliSDKTest", "key": "stream23126041129_1"} False ``` -#### Enable a Stream - -```python -stream.disable() -stream = hub.get(stream_title1) -stream.disable() -print "before enable:", stream.refresh(), stream.disabled() -stream.enable() -print "after enable:", stream.refresh(), stream.disabled() -# before enable: {"disabledTill": -1, "converts": [], "hub": "PiliSDKTest", "key": "stream23126041129_1"} True -# after enable: {"disabledTill": 0, "converts": [], "hub": "PiliSDKTest", "key": "stream23126041129_1"} False -``` - #### Get Stream live status ```python @@ -259,7 +251,84 @@ print "after update converts:", stream.refresh() ```python now = int(time.time()) -print "get publish history:" +print "get publish history print stream.history(start_second=now-86400) # [{u'start': 1488359927, u'end': 1488367483}, {u'start': 1488348110, u'end': 1488358759}, {u'start': 1488338678, u'end': 1488340383}, {u'start': 1488333270, u'end': 1488337953}, {u'start': 1488282646, u'end': 1488288321}] ``` + + +### Room + +#### Instantiate a Pili Room + +```python +mac = pili.Mac(AccessKey, SecretKey) +room = RoomClient(mac) +``` + +#### Create Room + +```python +resp = room.create_room('admin_user', 'roomname') +print(resp.status_code) +print(resp.headers) +print(resp.text) +#200 +#{'Content-Length': '24', 'X-Whom': 'bc196', 'Vary': 'Accept-Encoding', 'Server': 'nginx/1.8.0', 'X-Log': 'PILI-RTC:1', 'Connection': 'keep-alive', 'X-Reqid': 'bccmalhRqam8WsO_', 'Date': 'Thu, 29 Mar 2018 08:54:01 GMT', 'Content-Type': 'application/json'} +#{"room_name":"roomname"} +``` + +#### Create Token + +````python +print(room.roomToken('roomname', 'admin_user', 'admin', 3600)) +```` + +#### Delete Room + +````python +resp = room.deleteRoom('roomname') +print(resp.status_code) +print(resp.headers) +print(resp.text) +#200 +#{'Content-Length': '2', 'X-Whom': 'bc197', 'Vary': 'Accept-Encoding', 'Server': 'nginx/1.8.0', 'X-Log': 'PILI-RTC:1', 'Connection': 'keep-alive', 'X-Reqid': 'GRkeCnQZB6q8WkvM', 'Date': 'Thu, 29 Mar 2018 08:55:35 GMT', 'Content-Type': 'application/json'} +#{} +```` + +#### Kick User + +````python +resp = room.kickUser('roomname', 'admin_user') +print(resp.status_code) +print(resp.headers) +print(resp.text) +#200 +#{'Content-Length': '33', 'Server': 'nginx/1.8.0', 'X-Log': 'PILI-RTC:169/500', 'Connection': 'keep-alive', 'X-Reqid': 'DT87e9Y39qq8WrN7, DT87e9Y39qq8WrN7', 'Date': 'Thu, 29 Mar 2018 08:59:34 GMT', 'Content-Type': 'application/json'} +#{} +```` + +#### Query Room + +````python +resp = room.getRoom('roomname') +print(resp.status_code) +print(resp.headers) +print(resp.text) +#200 +#{'Content-Length': '73', 'X-Whom': 'bc197', 'Vary': 'Accept-Encoding', 'Server': 'nginx/1.8.0', 'X-Log': 'PILI-RTC:213', 'Connection': 'keep-alive', 'X-Reqid': 'GRkeCnQZRqu8Wp3R, GRkeCnQZRqu8Wp3R', 'Date': 'Thu, 29 Mar 2018 09:00:55 GMT', 'Content-Type': 'application/json'} +#{"owner_id":"admin","room_name":"roomname","room_status":0,"user_max":10} +```` +#### Query User + +````python +resp = room.getUser('roomname') +print(resp.status_code) +print(resp.headers) +print(resp.text) +#200 +#{'Content-Length': '19', 'X-Whom': 'bc197', 'Vary': 'Accept-Encoding', 'Server': 'nginx/1.8.0', 'X-Log': 'PILI-RTC:197', 'Connection': 'keep-alive', 'X-Reqid': 'bccmalhRdqu8WnnH, bccmalhRdqu8WnnH', 'Date': 'Thu, 29 Mar 2018 09:01:43 GMT', 'Content-Type': 'application/json'} +#{"active_users":[]} +```` + + From 93c179dfa2c3012bbe7f18668e0618270642b357 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 17:21:02 +0800 Subject: [PATCH 28/37] adjust style --- interact_micro_example/kick_user.py | 2 +- interact_micro_example/query_user.py | 2 +- pili/auth.py | 35 +--------------------------- pili/hub.py | 3 ++- pili/roomClient.py | 12 +++++----- pili/stream.py | 2 +- pili/utils.py | 6 +++-- 7 files changed, 16 insertions(+), 46 deletions(-) diff --git a/interact_micro_example/kick_user.py b/interact_micro_example/kick_user.py index 634384f..c504387 100644 --- a/interact_micro_example/kick_user.py +++ b/interact_micro_example/kick_user.py @@ -12,7 +12,7 @@ room = RoomClient(mac) -resp = room.kickUser('roomname11111', 'admin_user') +resp = room.kickUser('roomname', 'admin_user') print(resp.status_code) print(resp.headers) diff --git a/interact_micro_example/query_user.py b/interact_micro_example/query_user.py index 8ef192b..fd19f97 100644 --- a/interact_micro_example/query_user.py +++ b/interact_micro_example/query_user.py @@ -12,7 +12,7 @@ room = RoomClient(mac) -resp = room.getUser('roomname11111') +resp = room.getUser('roomname') print(resp.status_code) print(resp.headers) diff --git a/pili/auth.py b/pili/auth.py index bdbb721..fb75850 100644 --- a/pili/auth.py +++ b/pili/auth.py @@ -3,7 +3,7 @@ auth_interface to create a function with auto generated authentication. """ from urlparse import urlparse -from .utils import send_and_decode, __hmac_sha1__ +from .utils import __hmac_sha1__ import pili.conf as conf @@ -50,36 +50,3 @@ def authed(self, method, url, body=None): headers.update({'User-Agent': conf.API_USERAGENT}) return headers - -def auth_interface(method): - """ - decorator takes func(**args) return req and change it to - func(auth, **args) return json result. - - Args: - func(**args) -> Request - - Returns: - func(**args) -> dict (decoded json) - """ - def authed(auth, **args): - """ - send request and decode response. Return the result in python format. - """ - req = method(**args) - - parsed = urlparse(req.get_full_url()) - raw_str = '%s %s' % (req.get_method(), parsed.path) - if parsed.query: - raw_str += '?%s' % (parsed.query) - raw_str += '\nHost: %s' % (parsed.netloc) - if req.has_data(): - raw_str += '\nContent-Type: application/json' - raw_str += "\n\n" - if req.has_data(): - raw_str += req.get_data() - req.add_header('Content-Type', 'application/json') - req.add_header('Authorization', auth.auth_interface_str(raw_str)) - req.add_header('User-Agent', conf.API_USERAGENT) - return send_and_decode(req) - return authed diff --git a/pili/hub.py b/pili/hub.py index a91a189..a64f671 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -1,10 +1,11 @@ # -*- coding: utf-8 -*- +import json + import pili.api as api from .stream import Stream from conf import API_HOST, API_VERSION from utils import normalize_path, normalize_data -import json class Hub(object): diff --git a/pili/roomClient.py b/pili/roomClient.py index 5b42de5..c6e9a00 100755 --- a/pili/roomClient.py +++ b/pili/roomClient.py @@ -2,9 +2,9 @@ import hashlib import json import time + import pili.api as api from utils import urlsafe_base64_encode - from conf import RTC_API_HOST @@ -48,8 +48,8 @@ def roomToken(self, roomName, userId, perm, expireAt, version='v2'): "user_id": userId, "perm": perm, "expire_at": int(time.time()) + expireAt} - roomAccessString = json.dumps(params, separators=(',', ':')) - encodedRoomAccess = urlsafe_base64_encode(roomAccessString) - hashed = hmac.new(self.__auth__.secret_key, encodedRoomAccess, hashlib.sha1) - encodedSign = urlsafe_base64_encode(hashed.digest()) - return self.__auth__.access_key+":"+encodedSign+":"+encodedRoomAccess + room_access_string = json.dumps(params, separators=(',', ':')) + encoded_room_access = urlsafe_base64_encode(room_access_string) + hashed = hmac.new(self.__auth__.secret_key, encoded_room_access, hashlib.sha1) + encoded_sign = urlsafe_base64_encode(hashed.digest()) + return self.__auth__.access_key+":"+encoded_sign+":"+encoded_room_access diff --git a/pili/stream.py b/pili/stream.py index be1c200..6c15b00 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -1,8 +1,8 @@ # -*- coding: utf-8 -*- import json -import time from base64 import urlsafe_b64encode + import pili.api as api from conf import API_HOST, API_VERSION from utils import normalize_path, normalize_data diff --git a/pili/utils.py b/pili/utils.py index 84d0455..bffe904 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -4,11 +4,12 @@ from urllib2 import urlopen, HTTPError import contextlib import json -from .errors import APIError import hmac import hashlib import base64 +from .errors import APIError + def send_and_decode(req): """ @@ -70,10 +71,11 @@ def normalize_path(args, keyword, url): url = url + '?' + path return url + def normalize_data(args, keyword): if set(args) - set(keyword): raise ValueError('invalid key') for k, v in args.items(): if v is None: del args[k] - return json.dumps(args) \ No newline at end of file + return json.dumps(args) From 7ba5f8cd90cb15813975370f03df97ce204a130f Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 17:24:22 +0800 Subject: [PATCH 29/37] test adjust --- tests/test_hub.py | 3 --- tests/test_room.py | 1 - 2 files changed, 4 deletions(-) diff --git a/tests/test_hub.py b/tests/test_hub.py index 1ecdd11..01c6891 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -7,7 +7,6 @@ import json from pili import Hub, Mac -from pili.conf import API_HOST def env(key): @@ -26,8 +25,6 @@ def setUp(self): if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") - if env("PILI_API_HOST") != "": - API_HOST = env("PILI_API_HOST") mac = Mac(access_key, secret_key) self.hub = Hub(mac, hub_name) diff --git a/tests/test_room.py b/tests/test_room.py index 243ec61..1a177f8 100644 --- a/tests/test_room.py +++ b/tests/test_room.py @@ -7,7 +7,6 @@ from pili import RoomClient, Mac - def env(key): if key in os.environ: return os.environ[key] From e29439b08114bdeac51f7d9bafa43d624e80bb08 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Thu, 29 Mar 2018 17:56:35 +0800 Subject: [PATCH 30/37] adjust python2 --- interact_micro_example/create_room.py | 3 +-- interact_micro_example/create_token.py | 2 +- interact_micro_example/delete_room.py | 2 +- interact_micro_example/kick_user.py | 2 +- interact_micro_example/query_room.py | 2 +- interact_micro_example/query_user.py | 2 +- live_examples/convert.py | 2 +- live_examples/create_steam.py | 4 ++-- live_examples/history_record.py | 4 ++-- live_examples/live_stream.py | 2 +- live_examples/live_streams.py | 2 +- live_examples/publish_play_url.py | 14 +++++++------- live_examples/save_playback.py | 2 +- live_examples/snapshot.py | 2 +- live_examples/stream_disable.py | 2 +- live_examples/streams.py | 2 +- operations_example/bandwidth_count_history.py | 3 ++- pili/__init__.py | 1 - pili/auth.py | 4 ++-- pili/compat.py | 2 ++ pili/hub.py | 4 ++-- pili/stream.py | 9 +++++---- pili/utils.py | 5 +++-- tests/test_stream.py | 6 ------ 24 files changed, 40 insertions(+), 43 deletions(-) diff --git a/interact_micro_example/create_room.py b/interact_micro_example/create_room.py index 4bcbb20..a8e1c0d 100644 --- a/interact_micro_example/create_room.py +++ b/interact_micro_example/create_room.py @@ -12,9 +12,8 @@ room = RoomClient(mac) -resp = room.create_room('admin_user', 'roomname') +resp = room.create_room('admin_user', 'room_name') print(resp.status_code) print(resp.headers) print(resp.text) - diff --git a/interact_micro_example/create_token.py b/interact_micro_example/create_token.py index 4ccdbe4..0007078 100644 --- a/interact_micro_example/create_token.py +++ b/interact_micro_example/create_token.py @@ -12,4 +12,4 @@ room = RoomClient(mac) -print(room.roomToken('roomname', 'admin_user', 'admin', 3600)) +print(room.roomToken('room_name', 'admin_user', 'admin', 3600)) diff --git a/interact_micro_example/delete_room.py b/interact_micro_example/delete_room.py index 40bf1aa..c63636f 100644 --- a/interact_micro_example/delete_room.py +++ b/interact_micro_example/delete_room.py @@ -12,7 +12,7 @@ room = RoomClient(mac) -resp = room.deleteRoom('roomname') +resp = room.deleteRoom('room_name') print(resp.status_code) print(resp.headers) diff --git a/interact_micro_example/kick_user.py b/interact_micro_example/kick_user.py index c504387..ba0a801 100644 --- a/interact_micro_example/kick_user.py +++ b/interact_micro_example/kick_user.py @@ -12,7 +12,7 @@ room = RoomClient(mac) -resp = room.kickUser('roomname', 'admin_user') +resp = room.kickUser('room_name', 'admin_user') print(resp.status_code) print(resp.headers) diff --git a/interact_micro_example/query_room.py b/interact_micro_example/query_room.py index 14cb6d8..50c53bf 100644 --- a/interact_micro_example/query_room.py +++ b/interact_micro_example/query_room.py @@ -12,7 +12,7 @@ room = RoomClient(mac) -resp = room.getRoom('roomname') +resp = room.getRoom('room_name') print(resp.status_code) print(resp.headers) diff --git a/interact_micro_example/query_user.py b/interact_micro_example/query_user.py index fd19f97..4b800a8 100644 --- a/interact_micro_example/query_user.py +++ b/interact_micro_example/query_user.py @@ -12,7 +12,7 @@ room = RoomClient(mac) -resp = room.getUser('roomname') +resp = room.getUser('room_name') print(resp.status_code) print(resp.headers) diff --git a/live_examples/convert.py b/live_examples/convert.py index 25c84c1..156b1eb 100644 --- a/live_examples/convert.py +++ b/live_examples/convert.py @@ -8,7 +8,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." mac = Mac(access_key, secret_key) diff --git a/live_examples/create_steam.py b/live_examples/create_steam.py index 9a47f9f..af40c61 100644 --- a/live_examples/create_steam.py +++ b/live_examples/create_steam.py @@ -8,9 +8,9 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." -stream_name = '...' +stream_name = "..." mac = Mac(access_key, secret_key) diff --git a/live_examples/history_record.py b/live_examples/history_record.py index 663b3c5..e20b8c6 100644 --- a/live_examples/history_record.py +++ b/live_examples/history_record.py @@ -8,9 +8,9 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." -stream_name = '123' +stream_name = "123" mac = Mac(access_key, secret_key) diff --git a/live_examples/live_stream.py b/live_examples/live_stream.py index c626a5c..14711af 100644 --- a/live_examples/live_stream.py +++ b/live_examples/live_stream.py @@ -8,7 +8,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." stream_name = "123" diff --git a/live_examples/live_streams.py b/live_examples/live_streams.py index da9a057..bf1f6ff 100644 --- a/live_examples/live_streams.py +++ b/live_examples/live_streams.py @@ -8,7 +8,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." stream_lists = ["123", "abc"] diff --git a/live_examples/publish_play_url.py b/live_examples/publish_play_url.py index dfbb5cc..ab6e61c 100644 --- a/live_examples/publish_play_url.py +++ b/live_examples/publish_play_url.py @@ -8,9 +8,9 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." -domain = '...' +domain = "..." stream_name = '123' @@ -27,12 +27,12 @@ https://developer.qiniu.com/pili/kb/1332/broadcast-authentication-mode https://developer.qiniu.com/pili/kb/2635/seven-cows-live-push-flow-authentication-md """ -print rtmp_publish_url(domain, hub_name, stream_name, mac, expire) +print(rtmp_publish_url(domain, hub_name, stream_name, mac, expire)) -# print rtmp_play_url(domain, hub_name, stream_name) +# print(rtmp_play_url(domain, hub_name, stream_name)) # -# print hls_play_url(domain, hub_name, stream_name) +# print(hls_play_url(domain, hub_name, stream_name)) # -# print hdl_play_url(domain, hub_name, stream_name) +# print(hdl_play_url(domain, hub_name, stream_name)) # -# print snapshot_play_url(domain, hub_name, stream_name) +# print(snapshot_play_url(domain, hub_name, stream_name)) diff --git a/live_examples/save_playback.py b/live_examples/save_playback.py index 0d6caf9..fdcc178 100644 --- a/live_examples/save_playback.py +++ b/live_examples/save_playback.py @@ -8,7 +8,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." stream_name = "123" diff --git a/live_examples/snapshot.py b/live_examples/snapshot.py index 7cd5a23..117ffe1 100644 --- a/live_examples/snapshot.py +++ b/live_examples/snapshot.py @@ -12,7 +12,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." stream_name = "..." diff --git a/live_examples/stream_disable.py b/live_examples/stream_disable.py index e7d78f0..6b498c1 100644 --- a/live_examples/stream_disable.py +++ b/live_examples/stream_disable.py @@ -8,7 +8,7 @@ # 替换成自己 Qiniu 账号的 SecretKey secret_key = "..." -hub_name = '...' +hub_name = "..." stream_name = "..." diff --git a/live_examples/streams.py b/live_examples/streams.py index 54ff021..b0b9d39 100644 --- a/live_examples/streams.py +++ b/live_examples/streams.py @@ -16,7 +16,7 @@ liveonly = False -prefix = "" +prefix = "..." limit = 100 diff --git a/operations_example/bandwidth_count_history.py b/operations_example/bandwidth_count_history.py index 2b9cf9a..89bfdb2 100644 --- a/operations_example/bandwidth_count_history.py +++ b/operations_example/bandwidth_count_history.py @@ -14,7 +14,8 @@ hub = Hub(mac, hub_name) -resp = hub.bandwidth_count_history(start=int(time.time())-100, end=int(time.time()), limit=100, marker=None) +resp = hub.bandwidth_count_history(start=int(time.time())-100, + end=int(time.time()), limit=100, marker=None) print(resp.status_code) print(resp.headers) diff --git a/pili/__init__.py b/pili/__init__.py index d71851a..1f00b15 100644 --- a/pili/__init__.py +++ b/pili/__init__.py @@ -1,6 +1,5 @@ from .errors import APIError # noqa from .auth import Mac # noqa from .urls import rtmp_publish_url, rtmp_play_url, hls_play_url, hdl_play_url, snapshot_play_url # noqa -import conf # noqa from .roomClient import RoomClient # noqa from .hub import Hub # noqa \ No newline at end of file diff --git a/pili/auth.py b/pili/auth.py index fb75850..54d67b1 100644 --- a/pili/auth.py +++ b/pili/auth.py @@ -2,9 +2,9 @@ Auth provide class Auth for authentication account. You can use decorator auth_interface to create a function with auto generated authentication. """ -from urlparse import urlparse -from .utils import __hmac_sha1__ +from .utils import __hmac_sha1__ +from .compat import urlparse import pili.conf as conf diff --git a/pili/compat.py b/pili/compat.py index 3333a58..e214493 100644 --- a/pili/compat.py +++ b/pili/compat.py @@ -33,6 +33,7 @@ if is_py2: from urlparse import urlparse # noqa + from urllib2 import urlopen, HTTPError import StringIO StringIO = BytesIO = StringIO.StringIO @@ -53,6 +54,7 @@ def u(data): elif is_py3: from urllib.parse import urlparse # noqa + from urllib.request import urlopen, HTTPError import io StringIO = io.StringIO BytesIO = io.BytesIO diff --git a/pili/hub.py b/pili/hub.py index a64f671..ac70c7f 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -4,8 +4,8 @@ import pili.api as api from .stream import Stream -from conf import API_HOST, API_VERSION -from utils import normalize_path, normalize_data +from .conf import API_HOST, API_VERSION +from .utils import normalize_path, normalize_data class Hub(object): diff --git a/pili/stream.py b/pili/stream.py index 6c15b00..f2febad 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -1,11 +1,12 @@ # -*- coding: utf-8 -*- import json + from base64 import urlsafe_b64encode import pili.api as api -from conf import API_HOST, API_VERSION -from utils import normalize_path, normalize_data +from .conf import API_HOST, API_VERSION +from .utils import normalize_path, normalize_data class Stream(object): @@ -29,8 +30,8 @@ def __getattr__(self, attr): self.refresh() try: return self.__data__ if attr == "data" else self.__data__[attr] - except KeyError, e: - return e.message + except KeyError as e: + return e def __repr__(self): return self.to_json() diff --git a/pili/utils.py b/pili/utils.py index bffe904..767c2f3 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -1,13 +1,14 @@ """ Utils """ -from urllib2 import urlopen, HTTPError + import contextlib import json import hmac import hashlib import base64 +from .compat import urlopen, HTTPError from .errors import APIError @@ -27,7 +28,7 @@ def send_and_decode(req): return None raw = res.read() return json.loads(raw) - except HTTPError, res: + except HTTPError as res: raw = res.read() try: data = json.loads(raw) diff --git a/tests/test_stream.py b/tests/test_stream.py index 30c13e5..1b36dad 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -24,8 +24,6 @@ def setUp(self): secret_key = env("secret_key") if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") - if env("PILI_API_HOST") != "": - API_HOST = env("PILI_API_HOST") mac = Mac(access_key, secret_key) self.hub = Hub(mac, hub_name) self.stream_title = "streamTest" + str(int(random.random()*1e10)) @@ -67,10 +65,6 @@ def test_stream_saveas(self): ret = stream.save_as(start=now - 20, end=now, fname="test1.mp4", format="mp4") self.assertEqual(ret["fname"], "test1.mp4") self.assertTrue(ret["persistentID"]) - try: - stream.save_as(now - 20, now, format="mp4", pipeline="notexist") - except Exception, e: - self.assertEqual(str(e), "no such pipeline") # 这个测试需要维持推流test1 def test_stream_snashot(self): From 50d8e1b13e99d57b6770d5e5a37fc5175c8529dd Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 30 Mar 2018 10:57:22 +0800 Subject: [PATCH 31/37] test hub --- pili/auth.py | 4 ++-- pili/hub.py | 2 +- pili/roomClient.py | 4 ++-- pili/utils.py | 29 +++++++++++----------------- tests/test_hub.py | 47 ++++++++++++++++++++++++++++++++++++++++------ 5 files changed, 57 insertions(+), 29 deletions(-) diff --git a/pili/auth.py b/pili/auth.py index 54d67b1..314be71 100644 --- a/pili/auth.py +++ b/pili/auth.py @@ -4,7 +4,7 @@ """ from .utils import __hmac_sha1__ -from .compat import urlparse +from .compat import urlparse, b import pili.conf as conf @@ -22,7 +22,7 @@ class Auth store the access_key and secret_key for authentication. def __init__(self, access_key, secret_key): if not (access_key and secret_key): raise ValueError('invalid key') - self.access_key, self.secret_key = access_key, secret_key + self.access_key, self.secret_key = access_key, b(secret_key) def auth_interface_str(self, raw_str): """ diff --git a/pili/hub.py b/pili/hub.py index ac70c7f..ad0ca2d 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -72,7 +72,7 @@ def bandwidth_count_history(self, **kwargs): return api._get(url=url, auth=self.__auth__) def bandwidth_count_detail(self, time): - url = "http://{0}/{1}/hubs/{2}/stat/play/history/detail?time=%s".format(API_HOST, API_VERSION, self.__hub__, time) + url = "http://{0}/{1}/hubs/{2}/stat/play/history/detail?time={3}".format(API_HOST, API_VERSION, self.__hub__, time) return api._get(url, self.__auth__) def wm_crete(self, **kwargs): diff --git a/pili/roomClient.py b/pili/roomClient.py index c6e9a00..7d22791 100755 --- a/pili/roomClient.py +++ b/pili/roomClient.py @@ -4,8 +4,8 @@ import time import pili.api as api -from utils import urlsafe_base64_encode -from conf import RTC_API_HOST +from .utils import urlsafe_base64_encode +from .conf import RTC_API_HOST class RoomClient(object): diff --git a/pili/utils.py b/pili/utils.py index 767c2f3..0f01df5 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -7,8 +7,9 @@ import hmac import hashlib import base64 +from copy import deepcopy -from .compat import urlopen, HTTPError +from .compat import urlopen, HTTPError, b, s from .errors import APIError @@ -42,16 +43,9 @@ def __hmac_sha1__(data, key): """ hmac-sha1 """ + data = b(data) hashed = hmac.new(key, data, hashlib.sha1) - return base64.urlsafe_b64encode(hashed.digest()) - - -def b(data): - return bytes(data) - - -def s(data): - return bytes(data) + return urlsafe_base64_encode(hashed.digest()) def urlsafe_base64_encode(data): @@ -62,21 +56,20 @@ def urlsafe_base64_encode(data): def normalize_path(args, keyword, url): if set(args) - set(keyword): raise ValueError('invalid key') - for k, v in args.items(): - if v is None: - del args[k] path = '' for k, v in args.items(): - path += "&%s=%s" % (k, v) + if v: + path += "&%s=%s" % (k, v) if path: - url = url + '?' + path + url = url + '?' + path[1:] return url def normalize_data(args, keyword): if set(args) - set(keyword): raise ValueError('invalid key') + copy_args = deepcopy(args) for k, v in args.items(): - if v is None: - del args[k] - return json.dumps(args) + if not v: + del copy_args[k] + return json.dumps(copy_args) diff --git a/tests/test_hub.py b/tests/test_hub.py index 01c6891..e4f1770 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- import os -import unittest import time import random -import json +from json import loads +from unittest import TestCase, SkipTest from pili import Hub, Mac @@ -16,7 +16,7 @@ def env(key): return "" -class TestHubCases(unittest.TestCase): +class TestHubCases(TestCase): def setUp(self): hub_name = env("TEST_HUB") @@ -24,7 +24,7 @@ def setUp(self): secret_key = env("secret_key") if access_key == "" or secret_key == "": - raise unittest.SkipTest("need set access_key or secret_key") + raise SkipTest("need set access_key or secret_key") mac = Mac(access_key, secret_key) self.hub = Hub(mac, hub_name) @@ -32,14 +32,49 @@ def setUp(self): def test_batch_live_status(self): items = self.hub.batch_live_status(["test1", "test2"]) self.assertEqual(items.status_code, 200) - self.assertIn("test1", json.loads(items.text).get("items")[0].get("key")) + self.assertIn("test1", loads(items.text).get("items")[0].get("key")) def test_create_stream(self): self.stream_key = "streamtest" + str(int(random.random()*1e10))+str(time.time())[:10] items = self.hub.create(key=self.stream_key) self.assertEqual(items.status_code, 200) - self.assertEqual({}, json.loads(items.text)) + self.assertEqual({}, loads(items.text)) def test_query_streams(self): items = self.hub.get("test1") self.assertNotEqual(None, items) + + def test_wm_create(self): + test_name = "test" + str(int(time.time())) + items = self.hub.wm_crete(name=test_name, comment="for_test1", left='50%', + top='50%', width='10%', imageURL="http://omhrg3tgg.bkt.clouddn.com/413.png") + self.assertEqual(items.status_code, 200) + self.assertEqual(test_name, loads(items.text).get("name")) + items1 = self.hub.wm_crete(name="test1", comment="for_test1", left='50%', + top='50%', width='10%', imageURL="http://omhrg3tgg.bkt.clouddn.com/413.png") + self.assertEqual(items1.status_code, 614) + + def test_wm_download(self): + item = self.hub.wm_download(name="test1522373806") + self.assertEqual(item.status_code, 200) + + def test_wm_list(self): + items = self.hub.wm_list(limit=100) + self.assertIn("items", loads(items.text)) + + def test_wm_query(self): + items = self.hub.wm_query("test1") + self.assertEqual("test1", loads(items.text).get("name")) + + def test_bandwidth_detail(self): + items = self.hub.bandwidth_count_detail(str(int(time.time()))) + self.assertIn("items", loads(items.text)) + + def test_bandwidth_history(self): + items = self.hub.bandwidth_count_history(start=int(time.time()) - 100, + end=int(time.time()), limit=100, marker=None) + self.assertIn("items", loads(items.text)) + + def test_bandwidth_now(self): + items = self.hub.bandwidth_count_now() + self.assertIn("total", loads(items.text)) From 868725d0369660791438db4e522beabefdfb0ea8 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 30 Mar 2018 11:21:49 +0800 Subject: [PATCH 32/37] test pili --- pili/stream.py | 16 ++++++++-------- tests/test_stream.py | 43 ++++++++++++++++++++----------------------- 2 files changed, 28 insertions(+), 31 deletions(-) diff --git a/pili/stream.py b/pili/stream.py index f2febad..29a057d 100644 --- a/pili/stream.py +++ b/pili/stream.py @@ -2,9 +2,9 @@ import json -from base64 import urlsafe_b64encode import pili.api as api +from .utils import urlsafe_base64_encode from .conf import API_HOST, API_VERSION from .utils import normalize_path, normalize_data @@ -38,7 +38,7 @@ def __repr__(self): # refresh 主动更新流信息,会产生一次rpc调用 def refresh(self): - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s" % (API_HOST, API_VERSION, self.hub, key) data = api._get(url=url, auth=self.__auth__) self.__data__ = {} @@ -50,7 +50,7 @@ def refresh(self): # disable 禁用流,till Unix时间戳,在这之前流均不可用 def disable(self, till=None): - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/disabled" % (API_HOST, API_VERSION, self.hub, key) encoded = json.dumps({"disabledTill": till}) return api._post(url=url, data=encoded, auth=self.__auth__) @@ -67,7 +67,7 @@ def disable(self, till=None): data: 正整数,数据帧率 """ def status(self): - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/live" % (API_HOST, API_VERSION, self.hub, key) return api._get(url=url, auth=self.__auth__) @@ -81,7 +81,7 @@ def status(self): end: Unix时间戳,直播结束时间 """ def history(self, **kwargs): - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) keyword = ['start', 'end'] url = "http://{0}/{1}/hubs/{2}/streams/{3}/historyactivity?".format(API_HOST, API_VERSION, self.hub, key) url = normalize_path(kwargs, keyword, url) @@ -109,7 +109,7 @@ def save_as(self, **kwargs): persistentID: 异步模式时,持久化异步处理任务ID,通常用不到该字段 """ def saveas(self, **kwargs): - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/saveas" % (API_HOST, API_VERSION, self.hub, key) keyword = ['start', 'end', 'fname', 'format', 'pipeline', 'notify', 'expireDays'] encoded_data = normalize_data(kwargs, keyword) @@ -127,7 +127,7 @@ def saveas(self, **kwargs): def snapshot(self, **kwargs): keyword = ['time', 'fname', 'format'] encoded_data = normalize_data(kwargs, keyword) - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/snapshot" % (API_HOST, API_VERSION, self.hub, key) return api._post(url=url, auth=self.__auth__, data=encoded_data) @@ -138,7 +138,7 @@ def snapshot(self, **kwargs): 返回值: 无 """ def update_converts(self, profiles=[]): - key = urlsafe_b64encode(self.key) + key = urlsafe_base64_encode(self.key) url = "http://%s/%s/hubs/%s/streams/%s/converts" % (API_HOST, API_VERSION, self.hub, key) encoded_data = json.dumps({"converts": profiles}) return api._post(url=url, auth=self.__auth__, data=encoded_data) diff --git a/tests/test_stream.py b/tests/test_stream.py index 1b36dad..acbc341 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -3,8 +3,8 @@ import os import random import time -import unittest -import json +from unittest import TestCase, SkipTest +from json import loads from pili import Mac, Hub @@ -16,39 +16,36 @@ def env(key): return "" -class TestStreamCases(unittest.TestCase): +class TestStreamCases(TestCase): def setUp(self): hub_name = env("TEST_HUB") access_key = env("access_key") secret_key = env("secret_key") + if access_key == "" or secret_key == "": - raise unittest.SkipTest("need set access_key or secret_key") + raise SkipTest("need set access_key or secret_key") mac = Mac(access_key, secret_key) self.hub = Hub(mac, hub_name) self.stream_title = "streamTest" + str(int(random.random()*1e10)) def test_stream_create(self): - stream = self.hub.create(key=self.stream_title) - self.assertEqual(stream.hub, "PiliSDKTest") - self.assertEqual(stream.key, self.stream_title) + items = self.hub.create(key=self.stream_title) + self.assertEqual(items.status_code, 200) + self.assertEqual(loads(items.text), {}) def test_stream_disable(self): - stream = self.hub.create(key=self.stream_title) - self.assertEqual({}, json.loads(stream.disable(-1).text)) + self.hub.create(key=self.stream_title) + stream = self.hub.get(key=self.stream_title) + self.assertEqual({}, loads(stream.disable(-1).text)) self.assertEqual(-1, stream.refresh().get("disabledTill")) stream.disable(0) self.assertEqual(0, stream.refresh().get("disabledTill")) def test_stream_converts(self): - stream = self.hub.create(key=self.stream_title) - self.assertEqual(len(stream.converts), 0) + stream = self.hub.get(key="test1") stream.update_converts(["480p", "720p"]) - stream = stream.refresh() self.assertEqual(stream.converts, ["480p", "720p"]) - stream.update_converts() - stream = stream.refresh() - self.assertEqual(len(stream.converts), 0) # 这个测试需要维持推流test1 def test_stream_saveas(self): @@ -56,21 +53,21 @@ def test_stream_saveas(self): ret = stream.save_as() self.assertEqual(200, ret.status_code) now = int(time.time()) - ret = stream.saveas(start=now - 20) + ret = stream.saveas(start=now - 3600) self.assertIn(ret.status_code, (200, 619)) - ret = stream.save_as(start=now - 20, end=now) + ret = stream.save_as(start=now - 3600, end=now) self.assertIn(ret.status_code, (200, 619)) - ret = stream.saveas(start=now - 20, end=now, fname="test1.m3u8", format="m3u8") - self.assertEqual("test1.m3u8", json.loads(ret.text).get("fname")) - ret = stream.save_as(start=now - 20, end=now, fname="test1.mp4", format="mp4") - self.assertEqual(ret["fname"], "test1.mp4") - self.assertTrue(ret["persistentID"]) + ret = stream.saveas(start=now - 3600, end=now, fname="test1.m3u8", format="m3u8") + self.assertEqual(loads(ret.text).get("fname"), "test1.m3u8") + ret = stream.save_as(start=now - 3600, end=now, fname="test1.mp4", format="mp4") + self.assertEqual(loads(ret.text).get("fname"), "test1.mp4") + self.assertTrue(loads(ret.text).get("persistentID")) # 这个测试需要维持推流test1 def test_stream_snashot(self): stream = self.hub.get("test1") ret = stream.snapshot(fname="test1.jpg") - self.assertEqual(json.loads(ret.text)["fname"], "test1.jpg") + self.assertEqual(loads(ret.text)["fname"], "test1.jpg") # 这个测试需要维持推流test1 def test_stream_history(self): From d7deff7a8f4c1d4c4bc84226ad6ceb61c3fa3bdf Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 30 Mar 2018 11:32:09 +0800 Subject: [PATCH 33/37] test room --- pili/roomClient.py | 4 ++-- pili/utils.py | 8 ++++++-- tests/test_room.py | 8 ++++---- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/pili/roomClient.py b/pili/roomClient.py index 7d22791..de516f6 100755 --- a/pili/roomClient.py +++ b/pili/roomClient.py @@ -4,7 +4,7 @@ import time import pili.api as api -from .utils import urlsafe_base64_encode +from .utils import urlsafe_base64_encode, b from .conf import RTC_API_HOST @@ -50,6 +50,6 @@ def roomToken(self, roomName, userId, perm, expireAt, version='v2'): room_access_string = json.dumps(params, separators=(',', ':')) encoded_room_access = urlsafe_base64_encode(room_access_string) - hashed = hmac.new(self.__auth__.secret_key, encoded_room_access, hashlib.sha1) + hashed = hmac.new(self.__auth__.secret_key, b(encoded_room_access), hashlib.sha1) encoded_sign = urlsafe_base64_encode(hashed.digest()) return self.__auth__.access_key+":"+encoded_sign+":"+encoded_room_access diff --git a/pili/utils.py b/pili/utils.py index 0f01df5..7b6000b 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -6,7 +6,7 @@ import json import hmac import hashlib -import base64 +from base64 import urlsafe_b64encode, urlsafe_b64decode from copy import deepcopy from .compat import urlopen, HTTPError, b, s @@ -49,10 +49,14 @@ def __hmac_sha1__(data, key): def urlsafe_base64_encode(data): - ret = base64.urlsafe_b64encode(b(data)) + ret = urlsafe_b64encode(b(data)) return s(ret) +def urlsafe_base64_decode(data): + ret = urlsafe_b64decode(s(data)) + return ret + def normalize_path(args, keyword, url): if set(args) - set(keyword): raise ValueError('invalid key') diff --git a/tests/test_room.py b/tests/test_room.py index 1a177f8..0d2319f 100644 --- a/tests/test_room.py +++ b/tests/test_room.py @@ -5,6 +5,7 @@ import json from pili import RoomClient, Mac +from pili.utils import urlsafe_base64_decode def env(key): @@ -17,8 +18,8 @@ def env(key): class TestRoomCases(unittest.TestCase): def setUp(self): - access_key = env("access_key") - secret_key = env("secret_key") + access_key = "qUwQp6da8uMTpWjN-VLQ5o_B_dA-sZimFb7Zhq2u" + secret_key = "gKaLLT2xNXKfP-XiS5bZYS9-aOWJf5I6ymrPNdRK" if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") @@ -31,8 +32,7 @@ def test_create_room(self): def test_create_token(self): test_token = self.room.roomToken('roomname', 'admin_user', 'admin', 3600) - import base64 - decode_token = json.loads(base64.decodestring(test_token.split(":")[2])) + decode_token = json.loads(urlsafe_base64_decode(test_token.split(":")[2])) self.assertIn("admin_user", decode_token.get("user_id")) self.assertIn("2.0", decode_token.get("version")) self.assertIn("roomname", decode_token.get("room_name")) From fd0d2672bce8772c349f3fb1b46eb825b3ee0213 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 30 Mar 2018 11:37:04 +0800 Subject: [PATCH 34/37] fix aksk --- tests/test_room.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_room.py b/tests/test_room.py index 0d2319f..f3917a7 100644 --- a/tests/test_room.py +++ b/tests/test_room.py @@ -18,8 +18,8 @@ def env(key): class TestRoomCases(unittest.TestCase): def setUp(self): - access_key = "qUwQp6da8uMTpWjN-VLQ5o_B_dA-sZimFb7Zhq2u" - secret_key = "gKaLLT2xNXKfP-XiS5bZYS9-aOWJf5I6ymrPNdRK" + access_key = env("access_key") + secret_key = env("secret_key") if access_key == "" or secret_key == "": raise unittest.SkipTest("need set access_key or secret_key") From c0164e83a57eab87fd607f7f6a6e7ba26ff70be9 Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 30 Mar 2018 11:46:41 +0800 Subject: [PATCH 35/37] annotation --- live_examples/convert.py | 2 +- pili/api.py | 2 +- pili/conf.py | 2 +- pili/roomClient.py | 16 ++++++++-------- pili/utils.py | 1 + 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/live_examples/convert.py b/live_examples/convert.py index 156b1eb..f4600e3 100644 --- a/live_examples/convert.py +++ b/live_examples/convert.py @@ -18,7 +18,7 @@ resp = stream.update_converts(["480p", "720p"]) -# 建议打印headers方便向官方反馈问题,该接口调用成功是放回json为空{} +# 建议打印headers,方便向官方反馈问题,该接口调用成功会返回json为空{} print(resp.status_code) print(resp.headers) print(resp.text) diff --git a/pili/api.py b/pili/api.py index c278930..f8cd421 100644 --- a/pili/api.py +++ b/pili/api.py @@ -13,4 +13,4 @@ def _post(url, auth, data): def _delete(url, auth): hearders = auth.authed("DELETE", url) - return delete(url=url, headers=hearders) \ No newline at end of file + return delete(url=url, headers=hearders) diff --git a/pili/conf.py b/pili/conf.py index 13e20c0..f68e49a 100644 --- a/pili/conf.py +++ b/pili/conf.py @@ -9,5 +9,5 @@ API_HOST = 'pili.qiniuapi.com' API_USERAGENT = "pili-sdk-python/v2 %s %s" % (platform.python_version(), sys.platform) -RTC_API_VERSION = 'v1' +RTC_API_VERSION = 'v2' RTC_API_HOST = 'rtc.qiniuapi.com' diff --git a/pili/roomClient.py b/pili/roomClient.py index de516f6..40c140b 100755 --- a/pili/roomClient.py +++ b/pili/roomClient.py @@ -5,7 +5,7 @@ import pili.api as api from .utils import urlsafe_base64_encode, b -from .conf import RTC_API_HOST +from .conf import RTC_API_HOST, RTC_API_VERSION class RoomClient(object): @@ -14,7 +14,7 @@ def __init__(self, credentials): self.__credentials__ = credentials self.__auth__ = credentials.__auth__ - def create_room(self, ownerId, roomName=None, version='v2'): + def create_room(self, ownerId, roomName=None, version=RTC_API_VERSION): params = {'owner_id': ownerId} url = "http://%s/%s/rooms" % (RTC_API_HOST, version) if bool(roomName): @@ -22,24 +22,24 @@ def create_room(self, ownerId, roomName=None, version='v2'): encoded = json.dumps(params) return api._post(url=url, auth=self.__auth__, data=encoded) - def getRoom(self, roomName, version='v2'): + def getRoom(self, roomName, version=RTC_API_VERSION): url = "http://%s/%s/rooms/%s" % (RTC_API_HOST, version, roomName) return api._get(url=url, auth=self.__auth__) - def deleteRoom(self, roomName, version='v2'): + def deleteRoom(self, roomName, version=RTC_API_VERSION): url = "http://%s/%s/rooms/%s" % (RTC_API_HOST, version, roomName) return api._delete(url=url, auth=self.__auth__) - def getUser(self, roomName, version='v2'): + def getUser(self, roomName, version=RTC_API_VERSION): url = "http://%s/%s/rooms/%s/users" % (RTC_API_HOST, version, roomName) return api._get(url=url, auth=self.__auth__) - def kickUser(self, roomName, userId, version='v2'): + def kickUser(self, roomName, userId, version=RTC_API_VERSION): url = "http://%s/%s/rooms/%s/users/%s" % (RTC_API_HOST, version, roomName, userId) return api._delete(url=url, auth=self.__auth__) - def roomToken(self, roomName, userId, perm, expireAt, version='v2'): - if version == 'v2': + def roomToken(self, roomName, userId, perm, expireAt, version=RTC_API_VERSION): + if version == RTC_API_VERSION: params = {"version": "2.0", "room_name": roomName, "user_id": userId, "perm": perm, "expire_at": int(time.time()) + expireAt} diff --git a/pili/utils.py b/pili/utils.py index 7b6000b..e417327 100644 --- a/pili/utils.py +++ b/pili/utils.py @@ -57,6 +57,7 @@ def urlsafe_base64_decode(data): ret = urlsafe_b64decode(s(data)) return ret + def normalize_path(args, keyword, url): if set(args) - set(keyword): raise ValueError('invalid key') From ea4b11445b87b44d8206615ae1773d69411c01ec Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Mon, 2 Apr 2018 14:25:03 +0800 Subject: [PATCH 36/37] add document and link --- live_examples/convert.py | 6 ++++++ live_examples/create_steam.py | 6 ++++++ live_examples/history_record.py | 6 ++++++ live_examples/live_stream.py | 6 ++++++ live_examples/live_streams.py | 5 +++++ live_examples/publish_play_url.py | 15 ++++++++++----- live_examples/save_playback.py | 6 ++++++ live_examples/snapshot.py | 1 + live_examples/stream.py | 5 +++++ live_examples/stream_disable.py | 6 ++++++ live_examples/streams.py | 6 ++++++ tests/test_room.py | 2 -- 12 files changed, 63 insertions(+), 7 deletions(-) diff --git a/live_examples/convert.py b/live_examples/convert.py index f4600e3..537b0a6 100644 --- a/live_examples/convert.py +++ b/live_examples/convert.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2521/modify-the-flow-configuration +修改转码流配置 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/create_steam.py b/live_examples/create_steam.py index af40c61..c3c4414 100644 --- a/live_examples/create_steam.py +++ b/live_examples/create_steam.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2515/create-a-flow +创建流 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/history_record.py b/live_examples/history_record.py index e20b8c6..9c2985e 100644 --- a/live_examples/history_record.py +++ b/live_examples/history_record.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2778/live-history +单个直播流历史查询 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/live_stream.py b/live_examples/live_stream.py index 14711af..01d138b 100644 --- a/live_examples/live_stream.py +++ b/live_examples/live_stream.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2776/live-broadcast-of-real-time-information +单条流实时状态查询 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/live_streams.py b/live_examples/live_streams.py index bf1f6ff..97fdc31 100644 --- a/live_examples/live_streams.py +++ b/live_examples/live_streams.py @@ -1,5 +1,10 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/3764/batch-query-broadcast-real-time-information +批量获取实时流信息 +""" + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/publish_play_url.py b/live_examples/publish_play_url.py index ab6e61c..7fd81d6 100644 --- a/live_examples/publish_play_url.py +++ b/live_examples/publish_play_url.py @@ -1,5 +1,15 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2767/the-rtmp-push-flow-address +生成推流拉流及封面地址 + +该生成推流地址方法只适用于v2版本的限时鉴权,v2的无鉴权只需拼接域名,直播空间名和流名,v1版本的鉴权算法见下 +https://developer.qiniu.com/pili/kb/1332/broadcast-authentication-mode +https://developer.qiniu.com/pili/kb/2635/seven-cows-live-push-flow-authentication-md +""" + + from pili import Mac, Hub, rtmp_play_url, rtmp_publish_url, hdl_play_url, hls_play_url, snapshot_play_url # 替换成自己 Qiniu 账号的 AccessKey @@ -22,11 +32,6 @@ stream = hub.get(stream_name) -""" -该生成推流地址方法只适用于v2版本的限时鉴权,v2的无鉴权只需拼接域名,直播空间名和流名,v1版本的鉴权算法见下 -https://developer.qiniu.com/pili/kb/1332/broadcast-authentication-mode -https://developer.qiniu.com/pili/kb/2635/seven-cows-live-push-flow-authentication-md -""" print(rtmp_publish_url(domain, hub_name, stream_name, mac, expire)) # print(rtmp_play_url(domain, hub_name, stream_name)) diff --git a/live_examples/save_playback.py b/live_examples/save_playback.py index fdcc178..1e59e6e 100644 --- a/live_examples/save_playback.py +++ b/live_examples/save_playback.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2777/save-the-live-playback +录制直播回放 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/snapshot.py b/live_examples/snapshot.py index 117ffe1..63247f1 100644 --- a/live_examples/snapshot.py +++ b/live_examples/snapshot.py @@ -2,6 +2,7 @@ """ https://developer.qiniu.com/pili/api/2520/save-the-live-capture +保存直播截图 """ from pili import Mac, Hub diff --git a/live_examples/stream.py b/live_examples/stream.py index 9fbf014..1d114a6 100644 --- a/live_examples/stream.py +++ b/live_examples/stream.py @@ -1,5 +1,10 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2773/query-stream +查询流详情 +""" + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/stream_disable.py b/live_examples/stream_disable.py index 6b498c1..6d7cfb1 100644 --- a/live_examples/stream_disable.py +++ b/live_examples/stream_disable.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2775/off-the-air-flow +禁播流 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/live_examples/streams.py b/live_examples/streams.py index b0b9d39..c7094ac 100644 --- a/live_examples/streams.py +++ b/live_examples/streams.py @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- +""" +https://developer.qiniu.com/pili/api/2774/current-list +查询流列表 +""" + + from pili import Mac, Hub # 替换成自己 Qiniu 账号的 AccessKey diff --git a/tests/test_room.py b/tests/test_room.py index f3917a7..9215a26 100644 --- a/tests/test_room.py +++ b/tests/test_room.py @@ -50,5 +50,3 @@ def test_query_user(self): resp = self.room.getUser(roomName="roomname") decode_data = json.loads(resp.text) self.assertIn("active_users", decode_data) - - From aeef24ad9629bb2247aa89dd7bcc3b8fb0d6a58c Mon Sep 17 00:00:00 2001 From: bernieyangmh Date: Fri, 6 Apr 2018 21:04:42 +0800 Subject: [PATCH 37/37] pep8 --- interact_micro_example/kick_user.py | 3 --- live_examples/convert.py | 2 -- live_examples/live_stream.py | 2 -- live_examples/live_streams.py | 2 -- live_examples/publish_play_url.py | 14 +++++++------- live_examples/snapshot.py | 3 --- live_examples/stream_disable.py | 2 -- live_examples/streams.py | 1 - pili/auth.py | 1 - pili/hub.py | 9 ++++++++- tests/test_hub.py | 4 ++-- 11 files changed, 17 insertions(+), 26 deletions(-) diff --git a/interact_micro_example/kick_user.py b/interact_micro_example/kick_user.py index ba0a801..4277709 100644 --- a/interact_micro_example/kick_user.py +++ b/interact_micro_example/kick_user.py @@ -17,6 +17,3 @@ print(resp.status_code) print(resp.headers) print(resp.text) - - - diff --git a/live_examples/convert.py b/live_examples/convert.py index 537b0a6..3519ff4 100644 --- a/live_examples/convert.py +++ b/live_examples/convert.py @@ -28,5 +28,3 @@ print(resp.status_code) print(resp.headers) print(resp.text) - - diff --git a/live_examples/live_stream.py b/live_examples/live_stream.py index 01d138b..483bdb2 100644 --- a/live_examples/live_stream.py +++ b/live_examples/live_stream.py @@ -29,5 +29,3 @@ print(resp.status_code) print(resp.headers) print(resp.text) - - diff --git a/live_examples/live_streams.py b/live_examples/live_streams.py index 97fdc31..a9095c2 100644 --- a/live_examples/live_streams.py +++ b/live_examples/live_streams.py @@ -26,5 +26,3 @@ print(resp.status_code) print(resp.headers) print(resp.text) - - diff --git a/live_examples/publish_play_url.py b/live_examples/publish_play_url.py index 7fd81d6..8a26e24 100644 --- a/live_examples/publish_play_url.py +++ b/live_examples/publish_play_url.py @@ -34,10 +34,10 @@ print(rtmp_publish_url(domain, hub_name, stream_name, mac, expire)) -# print(rtmp_play_url(domain, hub_name, stream_name)) -# -# print(hls_play_url(domain, hub_name, stream_name)) -# -# print(hdl_play_url(domain, hub_name, stream_name)) -# -# print(snapshot_play_url(domain, hub_name, stream_name)) +print(rtmp_play_url(domain, hub_name, stream_name)) + +print(hls_play_url(domain, hub_name, stream_name)) + +print(hdl_play_url(domain, hub_name, stream_name)) + +print(snapshot_play_url(domain, hub_name, stream_name)) diff --git a/live_examples/snapshot.py b/live_examples/snapshot.py index 63247f1..81aa953 100644 --- a/live_examples/snapshot.py +++ b/live_examples/snapshot.py @@ -29,6 +29,3 @@ print(resp.status_code) print(resp.headers) print(resp.text) - - - diff --git a/live_examples/stream_disable.py b/live_examples/stream_disable.py index 6d7cfb1..5378366 100644 --- a/live_examples/stream_disable.py +++ b/live_examples/stream_disable.py @@ -28,5 +28,3 @@ stream.disable(till=1521710848) print(stream) - - diff --git a/live_examples/streams.py b/live_examples/streams.py index c7094ac..8401925 100644 --- a/live_examples/streams.py +++ b/live_examples/streams.py @@ -31,4 +31,3 @@ print(resp.status_code) print(resp.headers) print(resp.text) - diff --git a/pili/auth.py b/pili/auth.py index 314be71..3661b58 100644 --- a/pili/auth.py +++ b/pili/auth.py @@ -49,4 +49,3 @@ def authed(self, method, url, body=None): headers.update({'Authorization': self.auth_interface_str(raw_str)}) headers.update({'User-Agent': conf.API_USERAGENT}) return headers - diff --git a/pili/hub.py b/pili/hub.py index ad0ca2d..0fcfb1a 100644 --- a/pili/hub.py +++ b/pili/hub.py @@ -72,7 +72,8 @@ def bandwidth_count_history(self, **kwargs): return api._get(url=url, auth=self.__auth__) def bandwidth_count_detail(self, time): - url = "http://{0}/{1}/hubs/{2}/stat/play/history/detail?time={3}".format(API_HOST, API_VERSION, self.__hub__, time) + url = "http://{0}/{1}/hubs/{2}/stat/play/history/detail?time={3}".format(API_HOST, API_VERSION, + self.__hub__, time) return api._get(url, self.__auth__) def wm_crete(self, **kwargs): @@ -94,3 +95,9 @@ def wm_download(self, name): def wm_query(self, name): url = "http://{0}/{1}/hubs/{2}/watermarktemplate/{3}".format(API_HOST, API_VERSION, self.__hub__, name) return api._get(url=url, auth=self.__auth__) + + def se_qweszcdasf(self, **kwargs): + url = "http://{0}/{1}/hubs/{2}/security".format(API_HOST, API_VERSION, self.__hub__) + keyword = ["publishSecurity", "publishKey"] + encoded = normalize_data(kwargs, keyword) + return api._post(url=url, auth=self.__auth__, data=encoded) diff --git a/tests/test_hub.py b/tests/test_hub.py index e4f1770..b848235 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -47,11 +47,11 @@ def test_query_streams(self): def test_wm_create(self): test_name = "test" + str(int(time.time())) items = self.hub.wm_crete(name=test_name, comment="for_test1", left='50%', - top='50%', width='10%', imageURL="http://omhrg3tgg.bkt.clouddn.com/413.png") + top='50%', width='10%', imageURL="http://omhrg3tgg.bkt.clouddn.com/413.png") self.assertEqual(items.status_code, 200) self.assertEqual(test_name, loads(items.text).get("name")) items1 = self.hub.wm_crete(name="test1", comment="for_test1", left='50%', - top='50%', width='10%', imageURL="http://omhrg3tgg.bkt.clouddn.com/413.png") + top='50%', width='10%', imageURL="http://omhrg3tgg.bkt.clouddn.com/413.png") self.assertEqual(items1.status_code, 614) def test_wm_download(self):