StreamMedia.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. from django.views.generic.base import View
  2. from django.utils.decorators import method_decorator
  3. from django.views.decorators.csrf import csrf_exempt
  4. from Service.ModelService import ModelService
  5. from Model.models import Equipment_Stream
  6. from Object.AWS.S3ClassObject import S3ClassObject
  7. from Object.AWS.ElasticTranscoder import ElasticTranscoder
  8. import traceback, xmltodict, requests, re, subprocess, time, os,simplejson as json
  9. from ffmpy import FFmpeg
  10. from Object.AWS.CloudfrontSignCookie import BetterThanBoto
  11. from Ansjer.config import NGINX_RTMP_STAT, RTMP_PUSH_URL
  12. from Ansjer.config import BASE_DIR
  13. from Object.TokenObject import TokenObject
  14. from Object.ResponseObject import ResponseObject
  15. from Service.CommonService import CommonService
  16. from django.http import HttpResponse
  17. '''
  18. 移动端=>
  19. 增:
  20. http://192.168.136.40:8077/media/stream?token=test&channel=1&status=1&uid=1&operation=add
  21. 删:
  22. http://192.168.136.40:8077/media/stream?token=test&id=11&id=12&operation=delete
  23. 改:
  24. http://192.168.136.40:8077/media/stream?token=test&id=13&operation=update&status=0
  25. 查:
  26. http://192.168.136.40:8077/media/stream?token=test&operation=query
  27. 获取视频播放地址
  28. http://13.56.215.252:82/media/stream?token=test&channel=99&uid=2N1K3LE78TYJ38CE111A&filename=1526882855.flv&operation=getVodHls
  29. http://192.168.136.40:8077/media/stream?token=test&channel=1&uid=1&operation=getVodUrl&filename=1_1-1523247439.mp4
  30. 获取所有保存s3的视频
  31. http://192.168.136.40:8077/media/stream?token=test&channel=1&uid=1&operation=getAllVideo
  32. 删除设备视频多个,key值传多个即可
  33. http://192.168.136.40:8077/media/stream?token=test&key=UKPAH63V23U4ZHEB111A_1/UKPAH63V23U4ZHEB111A_1-1524039164.mp4&uid=UKPAH63V23U4ZHEB111A&channel=1&operation=getDelVideo
  34. ----------------------------------------------------------------------------------------------------
  35. 后台=>
  36. 验证推流权限
  37. http://192.168.136.40:8077/media/auth_stream?userID=151547867345163613800138001&uid=1&channel=1&access_token=test
  38. 验证播放权限(直播)
  39. http://192.168.136.40:8077/media/auth_live?userID=151547867345163613800138001&uid=1&channel=1&token=test
  40. rtmp://192.168.136.45:1935/hls/UKPAH63V23U4ZHEB111A_88?userID=151547867
  41. 获取所有推流的设备信息
  42. http://192.168.136.40:8077/media/stream?token=test&page=1&line=10&operation=getAdminAllStream
  43. 删除流
  44. http://192.168.136.40:8077/media/stream?token=test&id=1&id=2&id=3&operation=getAdminDelStream
  45. 删除指定设备视频
  46. http://192.168.136.40:8077/media/stream?token=test&key=1&key=2&key=3&operation=getAdminDelVideo
  47. 更新
  48. http://192.168.136.40:8077/media/stream?token=test&id=13&operation=getAdminUpdateStream&status=0
  49. 获取指定设备存储的视频播放地址
  50. http://192.168.136.40:8077/media/stream?token=test&channel=1&uid=1&filename=1_1-1523247439.mp4&operation=getAdminVodUrl
  51. hls播放
  52. http://13.56.215.252:82/media/stream?token=test&channel=1&status=1&uid=2N1K3LE78TYJ38CE111A&operation=add&rank=1
  53. '''
  54. class StreamMedia(View):
  55. @method_decorator(csrf_exempt)
  56. def dispatch(self, *args, **kwargs):
  57. return super(StreamMedia, self).dispatch(*args, **kwargs)
  58. def get(self, request, *args, **kwargs):
  59. request.encoding = 'utf-8'
  60. return self.validation(request_dict=request.GET)
  61. def post(self, request, *args, **kwargs):
  62. request.encoding = 'utf-8'
  63. return self.validation(request_dict=request.POST)
  64. def validation(self, request_dict, *args, **kwargs):
  65. response = ResponseObject()
  66. token = request_dict.get('token', None)
  67. if token is not None:
  68. tko = TokenObject(token)
  69. tko.valid()
  70. response.lang = tko.lang
  71. if tko.code == 0:
  72. userID = tko.userID
  73. own_permission = ModelService.check_permission(userID=userID, permID=60)
  74. if own_permission is not True:
  75. operation = request_dict.get('operation', None)
  76. if operation == 'add':
  77. return self.add_stream(token=token, request_dict=request_dict, userID=userID, response=response)
  78. elif operation == 'delete':
  79. return self.delete_stream(request_dict=request_dict, userID=userID, response=response)
  80. elif operation == 'update':
  81. return self.update_stream(userID=userID, request_dict=request_dict, response=response)
  82. elif operation == 'query':
  83. return self.query_stream(userID=userID, response=response)
  84. elif operation == 'getDelVideo':
  85. return self.get_del_video(userID=userID, request_dict=request_dict, response=response)
  86. elif operation == 'getAllVideo':
  87. return self.get_all_video(request_dict=request_dict, userID=userID, response=response)
  88. elif operation == 'getVodUrl':
  89. return self.get_vod_url(request_dict=request_dict, response=response)
  90. elif operation == 'getVodHls':
  91. return self.get_vod_hls(request_dict=request_dict, response=response)
  92. elif operation == 'getAdminAllStream':
  93. return self.get_admin_all_stream(request_dict=request_dict, userID=userID, response=response)
  94. elif operation == 'getAdminDelStream':
  95. return self.get_admin_del_stream(request_dict=request_dict, userID=userID, response=response)
  96. elif operation == 'getAdminUpdateStream':
  97. return self.get_admin_update_stream(request_dict=request_dict, userID=userID, response=response)
  98. elif operation == 'getAdminVodUrl':
  99. return self.get_admin_vod_url(request_dict=request_dict, userID=userID, response=response)
  100. elif operation == 'getAdminFindStream':
  101. return self.get_admin_find_stream(request_dict=request_dict, userID=userID, response=response)
  102. elif operation == 'getAdminDelVideo':
  103. return self.get_admin_del_video(request_dict=request_dict, userID=userID, response=response)
  104. elif operation == 'getAllServerJson':
  105. return self.get_all_server_json(userID=userID, response=response)
  106. elif operation == 'getAdminHlsVod':
  107. return self.get_admin_hls_vod(userID=userID, request_dict=request_dict, response=response)
  108. elif operation == 'getAdminAddStream':
  109. return self.get_admin_add_stream(userID=userID, request_dict=request_dict, response=response)
  110. else:
  111. return response.json(444, 'operation')
  112. else:
  113. return response.json(404)
  114. else:
  115. return response.json(tko.code)
  116. else:
  117. return response.json(309)
  118. def add_stream(self, token, userID, request_dict, response):
  119. channel = request_dict.get('channel', None)
  120. status = request_dict.get('status', None)
  121. uid = request_dict.get('uid', None)
  122. flag_param = CommonService.get_param_flag(data=[channel, status, uid])
  123. if flag_param is True:
  124. is_user = ModelService.check_own_device(userID=userID, UID=uid)
  125. if is_user is True:
  126. stream_queryset = Equipment_Stream.objects.filter(userID=userID, uid=uid, channel=channel, rank=1)
  127. if stream_queryset.exists():
  128. return response.json(174)
  129. try:
  130. flag = Equipment_Stream.objects.create(userID=userID, status=status, uid=uid, channel=channel,
  131. access_token=token)
  132. except Exception as e:
  133. errorInfo = traceback.format_exc()
  134. print(errorInfo)
  135. return response.json(424, errorInfo)
  136. else:
  137. if flag:
  138. rtmp_url = RTMP_PUSH_URL
  139. rtmp_name = uid + '_' + channel + '?userID=' + userID + '&uid=' + uid + '&channel=' + channel + '&access_token=' + token
  140. return response.json(0, {'userID': userID, 'channel': channel,
  141. 'uid': uid,
  142. 'status': status,
  143. 'access_token': token,
  144. 'rtmp_url': rtmp_url,
  145. 'rtmp_name': rtmp_name})
  146. else:
  147. return response.json(14)
  148. else:
  149. return response.json(444, 'channel, status, uid')
  150. def delete_stream(self, request_dict, userID,response):
  151. id_list = request_dict.getlist('id', None)
  152. if len(id_list):
  153. for id in id_list:
  154. Equipment_Stream.objects.filter(id=id, userID=userID).delete()
  155. return response.json(0)
  156. return response.json(444)
  157. def update_stream(self, userID, request_dict,response):
  158. id = request_dict.get('id', None)
  159. status = request_dict.get('status', None)
  160. is_update = Equipment_Stream.objects.filter(id=id, userID=userID).update(status=status)
  161. if is_update:
  162. return response.json(0, {'id': id, 'status': status})
  163. return response.json(444)
  164. def query_stream(self, userID,response):
  165. equipment_stream_queryset = Equipment_Stream.objects.filter(userID=userID)
  166. if equipment_stream_queryset.exists():
  167. res = CommonService.qs_to_dict(equipment_stream_queryset)
  168. return response.json(0,res)
  169. else:
  170. return response.json(0)
  171. def get_all_video(self, request_dict, userID,response):
  172. uid = request_dict.get('uid', None)
  173. channel = request_dict.get('channel', None)
  174. if uid is not None and channel is not None:
  175. own_permission = ModelService.check_permission(userID=userID, permID=30)
  176. own_device = ModelService.check_own_device(userID=userID, UID=uid)
  177. if own_permission is True or own_device is True:
  178. s3 = S3ClassObject()
  179. data = s3.get_all_object(prefix=uid + '_' + channel + '/flv')
  180. return response.json(0, {'files': data})
  181. else:
  182. return response.json(404)
  183. return response.json(444,'uid,channel')
  184. def get_vod_url(self, request_dict,response):
  185. uid = request_dict.get('uid', None)
  186. channel = request_dict.get('channel', None)
  187. filename = request_dict.get('filename', None)
  188. if uid is not None and filename is not None and channel is not None:
  189. s3 = S3ClassObject()
  190. url = s3.get_generate_vod_url(uid + '_' + channel + '/' + filename)
  191. return response.json(0, {'url': url})
  192. else:
  193. return response.json(444)
  194. def get_admin_all_stream(self, request_dict, userID,response):
  195. # 判断
  196. own_permission = ModelService.check_permission(userID=userID, permID=30)
  197. if own_permission is True:
  198. page = int(request_dict.get('page', None))
  199. line = int(request_dict.get('line', None))
  200. equipment_stream_queryset = Equipment_Stream.objects.all()
  201. if equipment_stream_queryset.exists():
  202. equipment_stream_count = equipment_stream_queryset.count()
  203. equipment_stream_res = equipment_stream_queryset[(page - 1) * line:page * line]
  204. send_json = CommonService.qs_to_dict(equipment_stream_res)
  205. send_json['count'] = equipment_stream_count
  206. send_json = CommonService.qs_to_dict(equipment_stream_queryset)
  207. return response.json(0, send_json)
  208. else:
  209. return response.json(0)
  210. else:
  211. return response.json(404)
  212. def get_admin_del_stream(self, request_dict, userID,response):
  213. # 判断
  214. own_permission = ModelService.check_permission(userID=userID, permID=10)
  215. if own_permission is True:
  216. id_list = request_dict.getlist('id', None)
  217. if len(id_list):
  218. for id in id_list:
  219. Equipment_Stream.objects.filter(id=id).delete()
  220. return response.json(0)
  221. else:
  222. return response.json(444)
  223. return response.json(404)
  224. def get_admin_del_video(self, request_dict, userID,response):
  225. # 判断
  226. own_permission = ModelService.check_permission(userID=userID, permID=10)
  227. if own_permission is True:
  228. key_list = request_dict.getlist('key', None)
  229. if len(key_list):
  230. uid = request_dict.get('uid', None)
  231. channel = request_dict.get('channel', None)
  232. if uid is not None and channel is not None:
  233. re_uid = re.compile(r'^' + uid + '_' + str(channel))
  234. re_flag = False
  235. print(key_list)
  236. for keys in key_list:
  237. re_flag = re_uid.match(keys)
  238. if re_flag is not True:
  239. break
  240. print(re_flag)
  241. if re_flag:
  242. s3 = S3ClassObject()
  243. response = s3.del_object_list(keylist=key_list)
  244. if response['Deleted']:
  245. return response.json(0,
  246. {'deleted': response['Deleted']})
  247. return response.json(444)
  248. def get_del_video(self, request_dict, userID,response):
  249. uid = request_dict.get('uid', None)
  250. channel = request_dict.get('channel', None)
  251. if uid is not None and channel is not None:
  252. own_permission = ModelService.check_own_device(userID=userID, UID=uid)
  253. if own_permission is True:
  254. key_list = request_dict.getlist('key', None)
  255. if len(key_list) > 0 and key_list is not None:
  256. re_uid = re.compile(r'^' + uid + '_' + str(channel))
  257. re_flag = False
  258. print(key_list)
  259. for keys in key_list:
  260. re_flag = re_uid.match(keys)
  261. if re_flag is not True:
  262. break
  263. if re_flag:
  264. s3 = S3ClassObject()
  265. response = s3.del_object_list(keylist=key_list)
  266. if response['Deleted']:
  267. return response.json(0)
  268. else:
  269. return response.json(404)
  270. return response.json(444)
  271. def get_admin_update_stream(self, userID, request_dict,response):
  272. own_permission = ModelService.check_permission(userID=userID, permID=50)
  273. if own_permission is True:
  274. id = request_dict.get('id', None)
  275. status = request_dict.get('status', None)
  276. param_flag = CommonService.get_param_flag(data=[status, id])
  277. if param_flag is True:
  278. is_update = Equipment_Stream.objects.filter(id=id).update(status=status)
  279. if is_update:
  280. return response.json(0, {'id': id, 'status': status})
  281. else:
  282. return response.json(444)
  283. else:
  284. return response.json(404)
  285. def get_admin_vod_url(self, userID, request_dict,response):
  286. own_permission = ModelService.check_permission(userID=userID, permID=30)
  287. if own_permission is True:
  288. uid = request_dict.get('uid', None)
  289. channel = request_dict.get('channel', None)
  290. filename = request_dict.get('filename', None)
  291. if uid is not None and filename is not None and channel is not None:
  292. s3 = S3ClassObject()
  293. url = s3.get_generate_vod_url(uid + '_' + channel + '/' + filename)
  294. return response.json(0, {'url': url})
  295. else:
  296. return response.json(444)
  297. else:
  298. return response.json(404)
  299. def get_admin_find_stream(self, userID, request_dict,response):
  300. own_permission = ModelService.check_permission(userID=userID, permID=20)
  301. if own_permission is True:
  302. content = request_dict.get('content', None)
  303. page = int(request_dict.get('page', None))
  304. line = int(request_dict.get('line', None))
  305. param_flag = CommonService.get_param_flag(data=[content, page, line])
  306. if param_flag is True:
  307. content = json.loads(content)
  308. search_kwargs = CommonService.get_kwargs(data=content)
  309. equipment_stream_queryset = Equipment_Stream.objects.filter(**search_kwargs)
  310. if equipment_stream_queryset.exists():
  311. equipment_stream_count = equipment_stream_queryset.count()
  312. equipment_stream_res = equipment_stream_queryset[(page - 1) * line:page * line]
  313. send_json = CommonService.qs_to_dict(equipment_stream_res)
  314. send_json['count'] = equipment_stream_count
  315. return response.json(0, send_json)
  316. else:
  317. return response.json(0)
  318. else:
  319. return response.json(444)
  320. else:
  321. return response.json(404)
  322. def get_all_server_json(self, userID,response):
  323. own_permission = ModelService.check_permission(userID=userID, permID=20)
  324. if own_permission is True:
  325. url = NGINX_RTMP_STAT
  326. res = requests.get(url)
  327. xml_content = res.text
  328. xml_dict = xmltodict.parse(xml_content)
  329. if len(xml_dict):
  330. return response.json(0, {'data': xml_dict})
  331. else:
  332. return response.json(404)
  333. def get_admin_add_stream(self, token, userID, request_dict,response):
  334. channel = request_dict.get('channel', None)
  335. status = request_dict.get('status', None)
  336. uid = request_dict.get('uid', None)
  337. flag_param = CommonService.get_param_flag(data=[channel, status, uid])
  338. if flag_param is True:
  339. own_perm = ModelService.check_permission(userID=userID, permID=40)
  340. if own_perm is True:
  341. stream_queryset = Equipment_Stream.objects.filter(uid=uid, channel=channel)
  342. if stream_queryset.exists():
  343. return response.json(174)
  344. try:
  345. flag = Equipment_Stream.objects.create(userID=userID, status=status, uid=uid, channel=channel,
  346. access_token=token)
  347. except Exception as e:
  348. errorInfo = traceback.format_exc()
  349. print(errorInfo)
  350. return response.json(424, {'details': errorInfo})
  351. else:
  352. if flag:
  353. rtmp_url = RTMP_PUSH_URL
  354. rtmp_name = uid + '_' + channel + '?userID=' + userID + '&uid=' + uid + '&channel=' + channel + '&access_token=' + token
  355. return response.json(0,
  356. {'userID': userID, 'channel': channel,
  357. 'uid': uid,
  358. 'status': status,
  359. 'access_token': token,
  360. 'rtmp_url': rtmp_url,
  361. 'rtmp_name': rtmp_name})
  362. else:
  363. return response.json(404)
  364. else:
  365. return response.json(444)
  366. def get_admin_hls_vod(self, request_dict, userID,response):
  367. own_permission = ModelService.check_permission(userID=userID, permID=30)
  368. if own_permission is True:
  369. uid = request_dict.get('uid', None)
  370. channel = request_dict.get('channel', None)
  371. filename = request_dict.get('filename', None)
  372. param_flag = CommonService.get_param_flag(data=[uid, filename, channel])
  373. if param_flag is True:
  374. uid_channel = uid + '_' + channel
  375. InputKey = uid_channel + '/flv/' + filename
  376. ts = filename.split('.')[0]
  377. vod_key = uid_channel + '/' + ts
  378. elastictranscoder = ElasticTranscoder()
  379. res = elastictranscoder.create_job(
  380. # InputKey='2N1K3LE78TYJ38CE111A_99/flv/1526882855.flv',
  381. InputKey=InputKey,
  382. # OutputKey='vod/2N1K3LE78TYJ38CE111A_99/1526882855'
  383. OutputKey='vod/' + vod_key
  384. )
  385. if res is True:
  386. domain_prefix = 'http://d3596w5a6euckc.cloudfront.net/vod'
  387. vod_url = domain_prefix + '/' + vod_key + '.m3u8'
  388. return response.json(0, {'vodurl': vod_url})
  389. else:
  390. return response.json(403)
  391. else:
  392. return response.json(444)
  393. else:
  394. return response.json(404)
  395. def get_vod_hls(self, request_dict,response):
  396. uid = request_dict.get('uid', None)
  397. channel = request_dict.get('channel', None)
  398. filename = request_dict.get('filename', None)
  399. param_flag = CommonService.get_param_flag(data=[uid, filename, channel])
  400. if param_flag is True:
  401. uid_channel = uid + '_' + channel
  402. InputKey = uid_channel + '/flv/' + filename
  403. ts = filename.split('.')[0]
  404. vod_key = uid_channel + '/' + ts
  405. elastictranscoder = ElasticTranscoder()
  406. res = elastictranscoder.create_job(
  407. InputKey=InputKey,
  408. OutputKey='vod/' + vod_key
  409. )
  410. if res is True:
  411. domain_prefix = 'http://d3596w5a6euckc.cloudfront.net/vod'
  412. vod_url = domain_prefix + '/' + vod_key + '.m3u8'
  413. vod_cookie_url = domain_prefix + '/' + uid_channel + '/*'
  414. expires_at = int(time.time()) + 7200
  415. cf = BetterThanBoto()
  416. vodCookie = cf.create_signed_cookies(url=vod_cookie_url, keypair_id="APKAINI6BNPKV54NHH7Q",
  417. expires_at=expires_at,
  418. private_key_file=os.path.join(BASE_DIR,
  419. 'Ansjer/file/pk-APKAINI6BNPKV54NHH7Q.pem'))
  420. return response.json(0, {'vodurl': vod_url, 'vodCookie': vodCookie})
  421. else:
  422. return response.json(403)
  423. else:
  424. return response.json(444)
  425. # 推流验证
  426. @csrf_exempt
  427. def Auth_Stream(request, *callback_args,
  428. **callback_kwargs):
  429. if request.method == 'GET':
  430. request.encoding = 'utf-8'
  431. request_dict = request.GET
  432. if request.method == 'POST':
  433. request.encoding = 'utf-8'
  434. request_dict = request.POST
  435. access_token = request_dict.get('access_token', None)
  436. userID = request_dict.get('userID', None)
  437. uid = request_dict.get('uid', None)
  438. channel = request_dict.get('channel', None)
  439. param_flag = CommonService.get_param_flag(data=[access_token, userID, uid, channel])
  440. if param_flag is True:
  441. own_permission = ModelService.check_permission(userID=userID, permID=60)
  442. if own_permission is True:
  443. equipment_stream_queryset = Equipment_Stream.objects.filter(userID=userID, uid=uid, channel=channel,
  444. status=1, access_token=access_token)
  445. if equipment_stream_queryset.exists():
  446. return HttpResponse(status=200)
  447. return HttpResponse(status=404)
  448. # 播放验证
  449. @csrf_exempt
  450. def Auth_Live(request, *callback_args,
  451. **callback_kwargs):
  452. if request.method == 'GET':
  453. request.encoding = 'utf-8'
  454. request_dict = request.GET
  455. if request.method == 'POST':
  456. request.encoding = 'utf-8'
  457. request_dict = request.POST
  458. response = ResponseObject()
  459. token = request_dict.get('token', None)
  460. if token is not None:
  461. tko = TokenObject(token)
  462. tko.valid()
  463. response.lang = tko.lang
  464. if tko.code == 0:
  465. userID = tko.userID
  466. uid = request_dict.get('uid', None)
  467. channel = request_dict.get('channel', None)
  468. if userID is not None and uid is not None and channel is not None:
  469. own_permission = ModelService.check_permission(userID=userID, permID=90)
  470. if own_permission is True:
  471. equipment_stream_queryset = Equipment_Stream.objects.filter(userID=userID, uid=uid, channel=channel,
  472. status=1)
  473. if equipment_stream_queryset.exists():
  474. return HttpResponse(status=200)
  475. return HttpResponse(status=404)
  476. @csrf_exempt
  477. def send_video_s3(request, *callback_args,
  478. **callback_kwargs):
  479. if request.method == 'GET':
  480. request.encoding = 'utf-8'
  481. request_dict = request.GET
  482. if request.method == 'POST':
  483. request.encoding = 'utf-8'
  484. request_dict = request.POST
  485. # 文件名
  486. basename = request_dict.get('basename', None)
  487. print(basename)
  488. if basename != None:
  489. base_path = '/tmp/flv/'
  490. file_base_path = base_path + basename
  491. input_path = file_base_path + '.flv'
  492. output_path = file_base_path + '.mp4'
  493. if os.path.exists(input_path):
  494. uid_channel = basename.split('-')[0]
  495. uid = uid_channel.split('_')[0]
  496. channel = uid_channel.split('_')[1]
  497. equipment_stream_queryset = Equipment_Stream.objects.filter(channel=channel, uid=uid, status=1)
  498. if equipment_stream_queryset.exists():
  499. try:
  500. key = uid_channel + '/' + basename + '.mp4'
  501. # 转换到
  502. ff = FFmpeg(
  503. inputs={input_path: None},
  504. outputs={output_path: ['-vcodec', 'copy', '-strict', '-2']}
  505. )
  506. ff.run()
  507. # 截取第一帧当缩略图
  508. # ffmpeg -i 555.flv -y -f image2 -ss 08.010 -t 0.001 -s 352x240 b.jpg
  509. except Exception as e:
  510. errorInfo = traceback.format_exc()
  511. print(errorInfo)
  512. else:
  513. if os.path.exists(output_path):
  514. s3 = S3ClassObject()
  515. s3_response = s3.put_mp4_object(body=open(output_path, 'rb'), key=key)
  516. print(s3_response)
  517. if s3_response['ResponseMetadata']['HTTPStatusCode'] == 200:
  518. # 记录保存文件容量,由于此操作过于频繁入库,上线代码去掉
  519. file_size = CommonService.get_file_size(file_path=output_path, suffix_type='MB',
  520. decimal_point=2)
  521. size = equipment_stream_queryset[0].total_flow
  522. if size:
  523. pass
  524. else:
  525. size = 0
  526. equipment_stream_queryset.update(total_flow=size + file_size)
  527. #
  528. rm_common = 'rm ' + input_path + ' ' + output_path
  529. subprocess.Popen(rm_common, shell=True)
  530. return HttpResponse(status=200)
  531. else:
  532. rm_common = 'rm ' + input_path + ' ' + output_path
  533. print('respone error')
  534. subprocess.Popen(rm_common, shell=True)
  535. return HttpResponse(status=403)
  536. else:
  537. return HttpResponse(404)
  538. @csrf_exempt
  539. def push_flv_s3(request, *callback_args,
  540. **callback_kwargs):
  541. if request.method == 'GET':
  542. request.encoding = 'utf-8'
  543. request_dict = request.GET
  544. if request.method == 'POST':
  545. request.encoding = 'utf-8'
  546. request_dict = request.POST
  547. # 文件名
  548. basename = request_dict.get('basename', None)
  549. response = ResponseObject()
  550. if basename != None:
  551. base_path = 'tmp/flv/'
  552. file_base_path = base_path + basename
  553. flv_path = file_base_path + '.flv'
  554. if os.path.exists(flv_path):
  555. dict_file = basename.split('-')
  556. uid_channel = dict_file[0]
  557. file_time = dict_file[1]
  558. uid = uid_channel.split('_')[0]
  559. channel = uid_channel.split('_')[1]
  560. equipment_stream_queryset = Equipment_Stream.objects.filter(channel=channel, uid=uid, status=1)
  561. if equipment_stream_queryset.exists():
  562. try:
  563. jpg_path = file_base_path + '.jpg'
  564. # 截取第一帧当缩略图ffmpeg -i 2N1K3LE78TYJ38CE111A_99-1526882169.flv -y -f image2 -t 0.001 -s 352x240 a.jpg
  565. ff = FFmpeg(
  566. inputs={flv_path: None},
  567. outputs={jpg_path: ['-y', '-f', 'image2', '-t', '0.001', '-s', '352x240']}
  568. )
  569. ff.cmd
  570. ff.run()
  571. except Exception as e:
  572. errorInfo = traceback.format_exc()
  573. print(errorInfo)
  574. else:
  575. if os.path.exists(jpg_path):
  576. s3 = S3ClassObject()
  577. flv_key = uid_channel + '/flv/' + file_time + '.flv'
  578. jpg_key = uid_channel + '/jpg/' + file_time + '.jpg'
  579. try:
  580. flv_response = s3.put_object(body=open(flv_path, 'rb'), key=flv_key)
  581. jpg_response = s3.put_object(body=open(jpg_path, 'rb'), key=jpg_key)
  582. if flv_response['ResponseMetadata']['HTTPStatusCode'] == 200 and \
  583. jpg_response['ResponseMetadata']['HTTPStatusCode'] == 200:
  584. code = 0
  585. else:
  586. code = 444
  587. except Exception as e:
  588. print(repr(e))
  589. code = 444
  590. pass
  591. path_list = [flv_path, jpg_path]
  592. for i in path_list:
  593. try:
  594. os.remove(i)
  595. except Exception as e:
  596. print(repr(e))
  597. pass
  598. return response.json(code)
  599. return response.json(444)