server.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2013-2021 Winlin
  4. #
  5. # SPDX-License-Identifier: MIT
  6. #
  7. """
  8. the api-server is a default demo server for srs to call
  9. when srs get some event, for example, when client connect
  10. to srs, srs can invoke the http api of the api-server
  11. """
  12. import sys
  13. # reload sys model to enable the getdefaultencoding method.
  14. reload(sys)
  15. # set the default encoding to utf-8
  16. # using exec to set the encoding, to avoid error in IDE.
  17. exec("sys.setdefaultencoding('utf-8')")
  18. assert sys.getdefaultencoding().lower() == "utf-8"
  19. import os, json, time, datetime, cherrypy, threading, urllib2, shlex, subprocess
  20. import cherrypy.process.plugins
  21. # simple log functions.
  22. def trace(msg):
  23. date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  24. print "[%s][trace] %s"%(date, msg)
  25. # enable crossdomain access for js-client
  26. # define the following method:
  27. # def OPTIONS(self, *args, **kwargs)
  28. # enable_crossdomain()
  29. # invoke this method to enable js to request crossdomain.
  30. def enable_crossdomain():
  31. cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
  32. cherrypy.response.headers["Access-Control-Allow-Methods"] = "GET, POST, HEAD, PUT, DELETE"
  33. # generate allow headers for crossdomain.
  34. allow_headers = ["Cache-Control", "X-Proxy-Authorization", "X-Requested-With", "Content-Type"]
  35. cherrypy.response.headers["Access-Control-Allow-Headers"] = ",".join(allow_headers)
  36. # error codes definition
  37. class Error:
  38. # ok, success, completed.
  39. success = 0
  40. # error when parse json
  41. system_parse_json = 100
  42. # request action invalid
  43. request_invalid_action = 200
  44. # cdn node not exists
  45. cdn_node_not_exists = 201
  46. '''
  47. handle the clients requests: connect/disconnect vhost/app.
  48. '''
  49. class RESTClients(object):
  50. exposed = True
  51. def GET(self):
  52. enable_crossdomain()
  53. clients = {}
  54. return json.dumps(clients)
  55. '''
  56. for SRS hook: on_connect/on_close
  57. on_connect:
  58. when client connect to vhost/app, call the hook,
  59. the request in the POST data string is a object encode by json:
  60. {
  61. "action": "on_connect",
  62. "client_id": 1985,
  63. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  64. "tcUrl": "rtmp://video.test.com/live?key=d2fa801d08e3f90ed1e1670e6e52651a",
  65. "pageUrl": "http://www.test.com/live.html"
  66. }
  67. on_close:
  68. when client close/disconnect to vhost/app/stream, call the hook,
  69. the request in the POST data string is a object encode by json:
  70. {
  71. "action": "on_close",
  72. "client_id": 1985,
  73. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  74. "send_bytes": 10240, "recv_bytes": 10240
  75. }
  76. if valid, the hook must return HTTP code 200(Stauts OK) and response
  77. an int value specifies the error code(0 corresponding to success):
  78. 0
  79. '''
  80. def POST(self):
  81. enable_crossdomain()
  82. # return the error code in str
  83. code = Error.success
  84. req = cherrypy.request.body.read()
  85. trace("post to clients, req=%s"%(req))
  86. try:
  87. json_req = json.loads(req)
  88. except Exception, ex:
  89. code = Error.system_parse_json
  90. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  91. return json.dumps({"code": int(code), "data": None})
  92. action = json_req["action"]
  93. if action == "on_connect":
  94. code = self.__on_connect(json_req)
  95. elif action == "on_close":
  96. code = self.__on_close(json_req)
  97. else:
  98. trace("invalid request action: %s"%(json_req["action"]))
  99. code = Error.request_invalid_action
  100. return json.dumps({"code": int(code), "data": None})
  101. def OPTIONS(self, *args, **kwargs):
  102. enable_crossdomain()
  103. def __on_connect(self, req):
  104. code = Error.success
  105. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, tcUrl=%s, pageUrl=%s"%(
  106. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["tcUrl"], req["pageUrl"]
  107. ))
  108. # TODO: process the on_connect event
  109. return code
  110. def __on_close(self, req):
  111. code = Error.success
  112. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, send_bytes=%s, recv_bytes=%s"%(
  113. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["send_bytes"], req["recv_bytes"]
  114. ))
  115. # TODO: process the on_close event
  116. return code
  117. '''
  118. handle the streams requests: publish/unpublish stream.
  119. '''
  120. class RESTStreams(object):
  121. exposed = True
  122. def GET(self):
  123. enable_crossdomain()
  124. streams = {}
  125. return json.dumps(streams)
  126. '''
  127. for SRS hook: on_publish/on_unpublish
  128. on_publish:
  129. when client(encoder) publish to vhost/app/stream, call the hook,
  130. the request in the POST data string is a object encode by json:
  131. {
  132. "action": "on_publish",
  133. "client_id": 1985,
  134. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  135. "stream": "livestream", "param":"?token=xxx&salt=yyy"
  136. }
  137. on_unpublish:
  138. when client(encoder) stop publish to vhost/app/stream, call the hook,
  139. the request in the POST data string is a object encode by json:
  140. {
  141. "action": "on_unpublish",
  142. "client_id": 1985,
  143. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  144. "stream": "livestream", "param":"?token=xxx&salt=yyy"
  145. }
  146. if valid, the hook must return HTTP code 200(Stauts OK) and response
  147. an int value specifies the error code(0 corresponding to success):
  148. 0
  149. '''
  150. def POST(self):
  151. enable_crossdomain()
  152. # return the error code in str
  153. code = Error.success
  154. req = cherrypy.request.body.read()
  155. trace("post to streams, req=%s"%(req))
  156. try:
  157. json_req = json.loads(req)
  158. except Exception, ex:
  159. code = Error.system_parse_json
  160. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  161. return json.dumps({"code": int(code), "data": None})
  162. action = json_req["action"]
  163. if action == "on_publish":
  164. code = self.__on_publish(json_req)
  165. elif action == "on_unpublish":
  166. code = self.__on_unpublish(json_req)
  167. else:
  168. trace("invalid request action: %s"%(json_req["action"]))
  169. code = Error.request_invalid_action
  170. return json.dumps({"code": int(code), "data": None})
  171. def OPTIONS(self, *args, **kwargs):
  172. enable_crossdomain()
  173. def __on_publish(self, req):
  174. code = Error.success
  175. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, stream=%s, param=%s"%(
  176. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["stream"], req["param"]
  177. ))
  178. # TODO: process the on_publish event
  179. return code
  180. def __on_unpublish(self, req):
  181. code = Error.success
  182. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, stream=%s, param=%s"%(
  183. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["stream"], req["param"]
  184. ))
  185. # TODO: process the on_unpublish event
  186. return code
  187. '''
  188. handle the dvrs requests: dvr stream.
  189. '''
  190. class RESTDvrs(object):
  191. exposed = True
  192. def GET(self):
  193. enable_crossdomain()
  194. dvrs = {}
  195. return json.dumps(dvrs)
  196. '''
  197. for SRS hook: on_dvr
  198. on_dvr:
  199. when srs reap a dvr file, call the hook,
  200. the request in the POST data string is a object encode by json:
  201. {
  202. "action": "on_dvr",
  203. "client_id": 1985,
  204. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  205. "stream": "livestream", "param":"?token=xxx&salt=yyy",
  206. "cwd": "/usr/local/srs",
  207. "file": "./objs/nginx/html/live/livestream.1420254068776.flv"
  208. }
  209. if valid, the hook must return HTTP code 200(Stauts OK) and response
  210. an int value specifies the error code(0 corresponding to success):
  211. 0
  212. '''
  213. def POST(self):
  214. enable_crossdomain()
  215. # return the error code in str
  216. code = Error.success
  217. req = cherrypy.request.body.read()
  218. trace("post to dvrs, req=%s"%(req))
  219. try:
  220. json_req = json.loads(req)
  221. except Exception, ex:
  222. code = Error.system_parse_json
  223. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  224. return json.dumps({"code": int(code), "data": None})
  225. action = json_req["action"]
  226. if action == "on_dvr":
  227. code = self.__on_dvr(json_req)
  228. else:
  229. trace("invalid request action: %s"%(json_req["action"]))
  230. code = Error.request_invalid_action
  231. return json.dumps({"code": int(code), "data": None})
  232. def OPTIONS(self, *args, **kwargs):
  233. enable_crossdomain()
  234. def __on_dvr(self, req):
  235. code = Error.success
  236. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, stream=%s, param=%s, cwd=%s, file=%s"%(
  237. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["stream"], req["param"],
  238. req["cwd"], req["file"]
  239. ))
  240. # TODO: process the on_dvr event
  241. return code
  242. '''
  243. handle the hls proxy requests: hls stream.
  244. '''
  245. class RESTProxy(object):
  246. exposed = True
  247. '''
  248. for SRS hook: on_hls_notify
  249. on_hls_notify:
  250. when srs reap a ts file of hls, call this hook,
  251. used to push file to cdn network, by get the ts file from cdn network.
  252. so we use HTTP GET and use the variable following:
  253. [app], replace with the app.
  254. [stream], replace with the stream.
  255. [param], replace with the param.
  256. [ts_url], replace with the ts url.
  257. ignore any return data of server.
  258. '''
  259. def GET(self, *args, **kwargs):
  260. enable_crossdomain()
  261. url = "http://" + "/".join(args);
  262. print "start to proxy url: %s"%url
  263. f = None
  264. try:
  265. f = urllib2.urlopen(url)
  266. f.read()
  267. except:
  268. print "error proxy url: %s"%url
  269. finally:
  270. if f: f.close()
  271. print "completed proxy url: %s"%url
  272. return url
  273. '''
  274. handle the hls requests: hls stream.
  275. '''
  276. class RESTHls(object):
  277. exposed = True
  278. '''
  279. for SRS hook: on_hls_notify
  280. on_hls_notify:
  281. when srs reap a ts file of hls, call this hook,
  282. used to push file to cdn network, by get the ts file from cdn network.
  283. so we use HTTP GET and use the variable following:
  284. [app], replace with the app.
  285. [stream], replace with the stream.
  286. [param], replace with the param.
  287. [ts_url], replace with the ts url.
  288. ignore any return data of server.
  289. '''
  290. def GET(self, *args, **kwargs):
  291. enable_crossdomain()
  292. hls = {
  293. "args": args,
  294. "kwargs": kwargs
  295. }
  296. return json.dumps(hls)
  297. '''
  298. for SRS hook: on_hls
  299. on_hls:
  300. when srs reap a dvr file, call the hook,
  301. the request in the POST data string is a object encode by json:
  302. {
  303. "action": "on_dvr",
  304. "client_id": 1985,
  305. "ip": "192.168.1.10",
  306. "vhost": "video.test.com",
  307. "app": "live",
  308. "stream": "livestream", "param":"?token=xxx&salt=yyy",
  309. "duration": 9.68, // in seconds
  310. "cwd": "/usr/local/srs",
  311. "file": "./objs/nginx/html/live/livestream.1420254068776-100.ts",
  312. "seq_no": 100
  313. }
  314. if valid, the hook must return HTTP code 200(Stauts OK) and response
  315. an int value specifies the error code(0 corresponding to success):
  316. 0
  317. '''
  318. def POST(self):
  319. enable_crossdomain()
  320. # return the error code in str
  321. code = Error.success
  322. req = cherrypy.request.body.read()
  323. trace("post to hls, req=%s"%(req))
  324. try:
  325. json_req = json.loads(req)
  326. except Exception, ex:
  327. code = Error.system_parse_json
  328. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  329. return json.dumps({"code": int(code), "data": None})
  330. action = json_req["action"]
  331. if action == "on_hls":
  332. code = self.__on_hls(json_req)
  333. else:
  334. trace("invalid request action: %s"%(json_req["action"]))
  335. code = Error.request_invalid_action
  336. return json.dumps({"code": int(code), "data": None})
  337. def OPTIONS(self, *args, **kwargs):
  338. enable_crossdomain()
  339. def __on_hls(self, req):
  340. code = Error.success
  341. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, stream=%s, param=%s, duration=%s, cwd=%s, file=%s, seq_no=%s"%(
  342. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["stream"], req["param"], req["duration"],
  343. req["cwd"], req["file"], req["seq_no"]
  344. ))
  345. # TODO: process the on_hls event
  346. return code
  347. '''
  348. handle the sessions requests: client play/stop stream
  349. '''
  350. class RESTSessions(object):
  351. exposed = True
  352. def GET(self):
  353. enable_crossdomain()
  354. sessions = {}
  355. return json.dumps(sessions)
  356. '''
  357. for SRS hook: on_play/on_stop
  358. on_play:
  359. when client(encoder) publish to vhost/app/stream, call the hook,
  360. the request in the POST data string is a object encode by json:
  361. {
  362. "action": "on_play",
  363. "client_id": 1985,
  364. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  365. "stream": "livestream", "param":"?token=xxx&salt=yyy",
  366. "pageUrl": "http://www.test.com/live.html"
  367. }
  368. on_stop:
  369. when client(encoder) stop publish to vhost/app/stream, call the hook,
  370. the request in the POST data string is a object encode by json:
  371. {
  372. "action": "on_stop",
  373. "client_id": 1985,
  374. "ip": "192.168.1.10", "vhost": "video.test.com", "app": "live",
  375. "stream": "livestream", "param":"?token=xxx&salt=yyy"
  376. }
  377. if valid, the hook must return HTTP code 200(Stauts OK) and response
  378. an int value specifies the error code(0 corresponding to success):
  379. 0
  380. '''
  381. def POST(self):
  382. enable_crossdomain()
  383. # return the error code in str
  384. code = Error.success
  385. req = cherrypy.request.body.read()
  386. trace("post to sessions, req=%s"%(req))
  387. try:
  388. json_req = json.loads(req)
  389. except Exception, ex:
  390. code = Error.system_parse_json
  391. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  392. return json.dumps({"code": int(code), "data": None})
  393. action = json_req["action"]
  394. if action == "on_play":
  395. code = self.__on_play(json_req)
  396. elif action == "on_stop":
  397. code = self.__on_stop(json_req)
  398. else:
  399. trace("invalid request action: %s"%(json_req["action"]))
  400. code = Error.request_invalid_action
  401. return json.dumps({"code": int(code), "data": None})
  402. def OPTIONS(self, *args, **kwargs):
  403. enable_crossdomain()
  404. def __on_play(self, req):
  405. code = Error.success
  406. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, stream=%s, param=%s, pageUrl=%s"%(
  407. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["stream"], req["param"], req["pageUrl"]
  408. ))
  409. # TODO: process the on_play event
  410. return code
  411. def __on_stop(self, req):
  412. code = Error.success
  413. trace("srs %s: client id=%s, ip=%s, vhost=%s, app=%s, stream=%s, param=%s"%(
  414. req["action"], req["client_id"], req["ip"], req["vhost"], req["app"], req["stream"], req["param"]
  415. ))
  416. # TODO: process the on_stop event
  417. return code
  418. global_arm_server_id = os.getpid();
  419. class ArmServer:
  420. def __init__(self):
  421. global global_arm_server_id
  422. global_arm_server_id += 1
  423. self.id = str(global_arm_server_id)
  424. self.ip = None
  425. self.device_id = None
  426. self.summaries = None
  427. self.devices = None
  428. self.public_ip = cherrypy.request.remote.ip
  429. self.heartbeat = time.time()
  430. self.clients = 0
  431. def dead(self):
  432. dead_time_seconds = 20
  433. if time.time() - self.heartbeat > dead_time_seconds:
  434. return True
  435. return False
  436. def json_dump(self):
  437. data = {}
  438. data["id"] = self.id
  439. data["ip"] = self.ip
  440. data["device_id"] = self.device_id
  441. data["summaries"] = self.summaries
  442. data["devices"] = self.devices
  443. data["public_ip"] = self.public_ip
  444. data["heartbeat"] = self.heartbeat
  445. data["heartbeat_h"] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(self.heartbeat))
  446. data["api"] = "http://%s:1985/api/v1/summaries"%(self.ip)
  447. data["console"] = "http://ossrs.net/console/ng_index.html#/summaries?host=%s&port=1985"%(self.ip)
  448. return data
  449. '''
  450. the server list
  451. '''
  452. class RESTServers(object):
  453. exposed = True
  454. def __init__(self):
  455. self.__nodes = []
  456. self.__last_update = datetime.datetime.now();
  457. self.__lock = threading.Lock()
  458. def __get_node(self, device_id):
  459. for node in self.__nodes:
  460. if node.device_id == device_id:
  461. return node
  462. return None
  463. def __refresh_nodes(self):
  464. while len(self.__nodes) > 0:
  465. has_dead_node = False
  466. for node in self.__nodes:
  467. if node.dead():
  468. self.__nodes.remove(node)
  469. has_dead_node = True
  470. if not has_dead_node:
  471. break
  472. '''
  473. post to update server ip.
  474. request body: the new raspberry-pi server ip. TODO: FIXME: more info.
  475. '''
  476. def POST(self):
  477. enable_crossdomain()
  478. try:
  479. self.__lock.acquire()
  480. req = cherrypy.request.body.read()
  481. trace("post to nodes, req=%s"%(req))
  482. try:
  483. json_req = json.loads(req)
  484. except Exception, ex:
  485. code = Error.system_parse_json
  486. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  487. return json.dumps({"code":code, "data": None})
  488. device_id = json_req["device_id"]
  489. node = self.__get_node(device_id)
  490. if node is None:
  491. node = ArmServer()
  492. self.__nodes.append(node)
  493. node.ip = json_req["ip"]
  494. if "summaries" in json_req:
  495. node.summaries = json_req["summaries"]
  496. if "devices" in json_req:
  497. node.devices = json_req["devices"]
  498. node.device_id = device_id
  499. node.public_ip = cherrypy.request.remote.ip
  500. node.heartbeat = time.time()
  501. return json.dumps({"code":Error.success, "data": {"id":node.id}})
  502. finally:
  503. self.__lock.release()
  504. '''
  505. get all servers which report to this api-server.
  506. '''
  507. def GET(self, id=None):
  508. enable_crossdomain()
  509. try:
  510. self.__lock.acquire()
  511. self.__refresh_nodes()
  512. data = []
  513. for node in self.__nodes:
  514. if id == None or node.id == str(id) or node.device_id == str(id):
  515. data.append(node.json_dump())
  516. return json.dumps(data)
  517. finally:
  518. self.__lock.release()
  519. def DELETE(self, id):
  520. enable_crossdomain()
  521. raise cherrypy.HTTPError(405, "Not allowed.")
  522. def PUT(self, id):
  523. enable_crossdomain()
  524. raise cherrypy.HTTPError(405, "Not allowed.")
  525. def OPTIONS(self, *args, **kwargs):
  526. enable_crossdomain()
  527. global_chat_id = os.getpid();
  528. '''
  529. the chat streams, public chat room.
  530. '''
  531. class RESTChats(object):
  532. exposed = True
  533. global_id = 100
  534. def __init__(self):
  535. # object fields:
  536. # id: an int value indicates the id of user.
  537. # username: a str indicates the user name.
  538. # url: a str indicates the url of user stream.
  539. # agent: a str indicates the agent of user.
  540. # join_date: a number indicates the join timestamp in seconds.
  541. # join_date_str: a str specifies the formated friendly time.
  542. # heatbeat: a number indicates the heartbeat timestamp in seconds.
  543. # vcodec: a dict indicates the video codec info.
  544. # acodec: a dict indicates the audio codec info.
  545. self.__chats = [];
  546. self.__chat_lock = threading.Lock();
  547. # dead time in seconds, if exceed, remove the chat.
  548. self.__dead_time = 15;
  549. '''
  550. get the rtmp url of chat object. None if overflow.
  551. '''
  552. def get_url_by_index(self, index):
  553. index = int(index)
  554. if index is None or index >= len(self.__chats):
  555. return None;
  556. return self.__chats[index]["url"];
  557. def GET(self):
  558. enable_crossdomain()
  559. try:
  560. self.__chat_lock.acquire();
  561. chats = [];
  562. copy = self.__chats[:];
  563. for chat in copy:
  564. if time.time() - chat["heartbeat"] > self.__dead_time:
  565. self.__chats.remove(chat);
  566. continue;
  567. chats.append({
  568. "id": chat["id"],
  569. "username": chat["username"],
  570. "url": chat["url"],
  571. "join_date_str": chat["join_date_str"],
  572. "heartbeat": chat["heartbeat"],
  573. });
  574. finally:
  575. self.__chat_lock.release();
  576. return json.dumps({"code":0, "data": {"now": time.time(), "chats": chats}})
  577. def POST(self):
  578. enable_crossdomain()
  579. req = cherrypy.request.body.read()
  580. chat = json.loads(req)
  581. global global_chat_id;
  582. chat["id"] = global_chat_id
  583. global_chat_id += 1
  584. chat["join_date"] = time.time();
  585. chat["heartbeat"] = time.time();
  586. chat["join_date_str"] = time.strftime("%Y-%m-%d %H:%M:%S");
  587. try:
  588. self.__chat_lock.acquire();
  589. self.__chats.append(chat)
  590. finally:
  591. self.__chat_lock.release();
  592. trace("create chat success, id=%s"%(chat["id"]))
  593. return json.dumps({"code":0, "data": chat["id"]})
  594. def DELETE(self, id):
  595. enable_crossdomain()
  596. try:
  597. self.__chat_lock.acquire();
  598. for chat in self.__chats:
  599. if str(id) != str(chat["id"]):
  600. continue
  601. self.__chats.remove(chat)
  602. trace("delete chat success, id=%s"%(id))
  603. return json.dumps({"code":0, "data": None})
  604. finally:
  605. self.__chat_lock.release();
  606. raise cherrypy.HTTPError(405, "Not allowed.")
  607. def PUT(self, id):
  608. enable_crossdomain()
  609. try:
  610. self.__chat_lock.acquire();
  611. for chat in self.__chats:
  612. if str(id) != str(chat["id"]):
  613. continue
  614. chat["heartbeat"] = time.time();
  615. trace("heartbeat chat success, id=%s"%(id))
  616. return json.dumps({"code":0, "data": None})
  617. finally:
  618. self.__chat_lock.release();
  619. raise cherrypy.HTTPError(405, "Not allowed.")
  620. def OPTIONS(self, *args, **kwargs):
  621. enable_crossdomain()
  622. '''
  623. the snapshot api,
  624. to start a snapshot when encoder start publish stream,
  625. stop the snapshot worker when stream finished.
  626. '''
  627. class RESTSnapshots(object):
  628. exposed = True
  629. def __init__(self):
  630. pass
  631. def POST(self):
  632. enable_crossdomain()
  633. # return the error code in str
  634. code = Error.success
  635. req = cherrypy.request.body.read()
  636. trace("post to streams, req=%s"%(req))
  637. try:
  638. json_req = json.loads(req)
  639. except Exception, ex:
  640. code = Error.system_parse_json
  641. trace("parse the request to json failed, req=%s, ex=%s, code=%s"%(req, ex, code))
  642. return json.dumps({"code": int(code), "data": None})
  643. action = json_req["action"]
  644. if action == "on_publish":
  645. code = worker.snapshot_create(json_req)
  646. elif action == "on_unpublish":
  647. code = worker.snapshot_destroy(json_req)
  648. else:
  649. trace("invalid request action: %s"%(json_req["action"]))
  650. code = Error.request_invalid_action
  651. return json.dumps({"code": int(code), "data": None})
  652. def OPTIONS(self, *args, **kwargs):
  653. enable_crossdomain()
  654. # HTTP RESTful path.
  655. class Root(object):
  656. exposed = True
  657. def __init__(self):
  658. self.api = Api()
  659. def GET(self):
  660. enable_crossdomain();
  661. return json.dumps({"code":Error.success, "urls":{"api":"the api root"}})
  662. def OPTIONS(self, *args, **kwargs):
  663. enable_crossdomain();
  664. # HTTP RESTful path.
  665. class Api(object):
  666. exposed = True
  667. def __init__(self):
  668. self.v1 = V1()
  669. def GET(self):
  670. enable_crossdomain();
  671. return json.dumps({"code":Error.success,
  672. "urls": {
  673. "v1": "the api version 1.0"
  674. }
  675. });
  676. def OPTIONS(self, *args, **kwargs):
  677. enable_crossdomain();
  678. # HTTP RESTful path. to access as:
  679. # http://127.0.0.1:8085/api/v1/clients
  680. class V1(object):
  681. exposed = True
  682. def __init__(self):
  683. self.clients = RESTClients()
  684. self.streams = RESTStreams()
  685. self.sessions = RESTSessions()
  686. self.dvrs = RESTDvrs()
  687. self.hls = RESTHls()
  688. self.proxy = RESTProxy()
  689. self.chats = RESTChats()
  690. self.servers = RESTServers()
  691. self.snapshots = RESTSnapshots()
  692. def GET(self):
  693. enable_crossdomain();
  694. return json.dumps({"code":Error.success, "urls":{
  695. "clients": "for srs http callback, to handle the clients requests: connect/disconnect vhost/app.",
  696. "streams": "for srs http callback, to handle the streams requests: publish/unpublish stream.",
  697. "sessions": "for srs http callback, to handle the sessions requests: client play/stop stream",
  698. "dvrs": "for srs http callback, to handle the dvr requests: dvr stream.",
  699. "chats": "for srs demo meeting, the chat streams, public chat room.",
  700. "servers": {
  701. "summary": "for srs raspberry-pi and meeting demo",
  702. "GET": "get the current raspberry-pi servers info",
  703. "POST ip=node_ip&device_id=device_id": "the new raspberry-pi server info."
  704. }
  705. }});
  706. def OPTIONS(self, *args, **kwargs):
  707. enable_crossdomain();
  708. '''
  709. main code start.
  710. '''
  711. # donot support use this module as library.
  712. if __name__ != "__main__":
  713. raise Exception("embed not support")
  714. # check the user options
  715. if len(sys.argv) <= 1:
  716. print "SRS api callback server, Copyright (c) 2013-2016 SRS(ossrs)"
  717. print "Usage: python %s <port>"%(sys.argv[0])
  718. print " port: the port to listen at."
  719. print "For example:"
  720. print " python %s 8085"%(sys.argv[0])
  721. print ""
  722. print "See also: https://github.com/ossrs/srs"
  723. sys.exit(1)
  724. # parse port from user options.
  725. port = int(sys.argv[1])
  726. static_dir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "static-dir"))
  727. trace("api server listen at port: %s, static_dir: %s"%(port, static_dir))
  728. discard = open("/dev/null", "rw")
  729. '''
  730. create process by specifies command.
  731. @param command the command str to start the process.
  732. @param stdout_fd an int fd specifies the stdout fd.
  733. @param stderr_fd an int fd specifies the stderr fd.
  734. @param log_file a file object specifies the additional log to write to. ignore if None.
  735. @return a Popen object created by subprocess.Popen().
  736. '''
  737. def create_process(command, stdout_fd, stderr_fd):
  738. # log the original command
  739. msg = "process start command: %s"%(command);
  740. # to avoid shell injection, directly use the command, no need to filter.
  741. args = shlex.split(str(command));
  742. process = subprocess.Popen(args, stdout=stdout_fd, stderr=stderr_fd);
  743. return process;
  744. '''
  745. isolate thread for srs worker, to do some job in background,
  746. for example, to snapshot thumbnail of RTMP stream.
  747. '''
  748. class SrsWorker(cherrypy.process.plugins.SimplePlugin):
  749. def __init__(self, bus):
  750. cherrypy.process.plugins.SimplePlugin.__init__(self, bus);
  751. self.__snapshots = {}
  752. def start(self):
  753. print "srs worker thread started"
  754. def stop(self):
  755. print "srs worker thread stopped"
  756. def main(self):
  757. for url in self.__snapshots:
  758. snapshot = self.__snapshots[url]
  759. diff = time.time() - snapshot['timestamp']
  760. process = snapshot['process']
  761. # aborted.
  762. if process is not None and snapshot['abort']:
  763. process.kill()
  764. process.poll()
  765. del self.__snapshots[url]
  766. print 'abort snapshot %s'%snapshot['cmd']
  767. break
  768. # how many snapshots to output.
  769. vframes = 5
  770. # the expire in seconds for ffmpeg to snapshot.
  771. expire = 1
  772. # the timeout to kill ffmpeg.
  773. kill_ffmpeg_timeout = 30 * expire
  774. # the ffmpeg binary path
  775. ffmpeg = "./objs/ffmpeg/bin/ffmpeg"
  776. # the best url for thumbnail.
  777. besturl = os.path.join(static_dir, "%s/%s-best.png"%(snapshot['app'], snapshot['stream']))
  778. # the lambda to generate the thumbnail with index.
  779. lgo = lambda dir, app, stream, index: os.path.join(dir, "%s/%s-%03d.png"%(app, stream, index))
  780. # the output for snapshot command
  781. output = os.path.join(static_dir, "%s/%s-%%03d.png"%(snapshot['app'], snapshot['stream']))
  782. # the ffmepg command to snapshot
  783. cmd = '%s -i %s -vf fps=1 -vcodec png -f image2 -an -y -vframes %s -y %s'%(ffmpeg, url, vframes, output)
  784. # already snapshoted and not expired.
  785. if process is not None and diff < expire:
  786. continue
  787. # terminate the active process
  788. if process is not None:
  789. # the poll will set the process.returncode
  790. process.poll()
  791. # None incidates the process hasn't terminate yet.
  792. if process.returncode is not None:
  793. # process terminated with error.
  794. if process.returncode != 0:
  795. print 'process terminated with error=%s, cmd=%s'%(process.returncode, snapshot['cmd'])
  796. # process terminated normally.
  797. else:
  798. # guess the best one.
  799. bestsize = 0
  800. for i in range(0, vframes):
  801. output = lgo(static_dir, snapshot['app'], snapshot['stream'], i + 1)
  802. fsize = os.path.getsize(output)
  803. if bestsize < fsize:
  804. os.system("rm -f '%s'"%besturl)
  805. os.system("ln -sf '%s' '%s'"%(output, besturl))
  806. bestsize = fsize
  807. print 'the best thumbnail is %s'%besturl
  808. else:
  809. # wait for process to terminate, timeout is N*expire.
  810. if diff < kill_ffmpeg_timeout:
  811. continue
  812. # kill the process when user cancel.
  813. else:
  814. process.kill()
  815. print 'kill the process %s'%snapshot['cmd']
  816. # create new process to snapshot.
  817. print 'snapshot by: %s'%cmd
  818. process = create_process(cmd, discard.fileno(), discard.fileno())
  819. snapshot['process'] = process
  820. snapshot['cmd'] = cmd
  821. snapshot['timestamp'] = time.time()
  822. pass;
  823. # {"action":"on_publish","client_id":108,"ip":"127.0.0.1","vhost":"__defaultVhost__","app":"live","stream":"livestream"}
  824. # ffmpeg -i rtmp://127.0.0.1:1935/live?vhost=dev/stream -vf fps=1 -vcodec png -f image2 -an -y -vframes 3 -y static-dir/live/livestream-%03d.png
  825. def snapshot_create(self, req):
  826. url = "rtmp://127.0.0.1/%s...vhost...%s/%s"%(req['app'], req['vhost'], req['stream'])
  827. if url in self.__snapshots:
  828. print 'ignore exists %s'%url
  829. return Error.success
  830. req['process'] = None
  831. req['abort'] = False
  832. req['timestamp'] = time.time()
  833. self.__snapshots[url] = req
  834. return Error.success
  835. # {"action":"on_unpublish","client_id":108,"ip":"127.0.0.1","vhost":"__defaultVhost__","app":"live","stream":"livestream"}
  836. def snapshot_destroy(self, req):
  837. url = "rtmp://127.0.0.1/%s...vhost...%s/%s"%(req['app'], req['vhost'], req['stream'])
  838. if url in self.__snapshots:
  839. snapshot = self.__snapshots[url]
  840. snapshot['abort'] = True
  841. return Error.success
  842. # subscribe the plugin to cherrypy.
  843. worker = SrsWorker(cherrypy.engine)
  844. worker.subscribe();
  845. # disable the autoreloader to make it more simple.
  846. cherrypy.engine.autoreload.unsubscribe();
  847. # cherrypy config.
  848. conf = {
  849. 'global': {
  850. 'server.shutdown_timeout': 3,
  851. 'server.socket_host': '0.0.0.0',
  852. 'server.socket_port': port,
  853. 'tools.encode.on': True,
  854. 'tools.staticdir.on': True,
  855. 'tools.encode.encoding': "utf-8",
  856. #'server.thread_pool': 2, # single thread server.
  857. },
  858. '/': {
  859. 'tools.staticdir.dir': static_dir,
  860. 'tools.staticdir.index': "index.html",
  861. # for cherrypy RESTful api support
  862. 'request.dispatch': cherrypy.dispatch.MethodDispatcher()
  863. }
  864. }
  865. # start cherrypy web engine
  866. trace("start cherrypy server")
  867. root = Root()
  868. cherrypy.quickstart(root, '/', conf)