|
@@ -0,0 +1,582 @@
|
|
1
|
+#!/bin/env python
|
|
2
|
+# -*- coding: utf-8 -*-
|
|
3
|
+"""
|
|
4
|
+Shortcut.lv proxy server
|
|
5
|
+
|
|
6
|
+usage: %s start|stop|restart|manualstart [options]
|
|
7
|
+ -p PORT - port number
|
|
8
|
+ -s WSGI_SERVER - wsgi server - wsgiref,cheroot,mtwsgi,waitress...
|
|
9
|
+ -d - debug printout
|
|
10
|
+ -r - remote debug mode (ptvsd)"""
|
|
11
|
+
|
|
12
|
+__version__ = "0.1a"
|
|
13
|
+
|
|
14
|
+import os, sys, time
|
|
15
|
+import urllib,urlparse, urllib2, requests
|
|
16
|
+from urllib import unquote, quote
|
|
17
|
+import re, json
|
|
18
|
+import ConfigParser, getopt
|
|
19
|
+import arrow
|
|
20
|
+from diskcache import Cache
|
|
21
|
+import daemonize
|
|
22
|
+import bottle
|
|
23
|
+from bottle import Bottle, hook, response, route, request, run
|
|
24
|
+
|
|
25
|
+cunicode = lambda s: s.decode("utf8") if isinstance(s, str) else s
|
|
26
|
+cstr = lambda s: s.encode("utf8") if isinstance(s, unicode) else s
|
|
27
|
+headers2dict = lambda h: dict([l.strip().split(": ") for l in h.strip().splitlines()])
|
|
28
|
+
|
|
29
|
+headers0 = headers2dict("""
|
|
30
|
+User-Agent: Shortcut.lv v2.9.1 / Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
|
|
31
|
+Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
|
|
32
|
+""")
|
|
33
|
+url0 = "https://manstv.lattelecom.tv/api/v1.7/get/content/"
|
|
34
|
+
|
|
35
|
+cur_directory = os.path.dirname(os.path.realpath(__file__))
|
|
36
|
+cache_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "cache")
|
|
37
|
+if not os.path.exists(cache_dir):
|
|
38
|
+ os.mkdir(cache_dir)
|
|
39
|
+
|
|
40
|
+config = ConfigParser.ConfigParser()
|
|
41
|
+proxy_cfg_file = os.path.join(cur_directory, "ltcproxy.cfg")
|
|
42
|
+
|
|
43
|
+DEBUG = False
|
|
44
|
+PORT_NUMBER = 8881
|
|
45
|
+REDIRECT = False
|
|
46
|
+CACHE = True
|
|
47
|
+KEY = ["0000","1111"]
|
|
48
|
+SERVER = "wsgiref"
|
|
49
|
+WORKERS = 10
|
|
50
|
+LTC_USER = "user"
|
|
51
|
+LTC_PASSWORD = "password"
|
|
52
|
+
|
|
53
|
+if not os.path.exists(proxy_cfg_file):
|
|
54
|
+ config.add_section("ltcproxy")
|
|
55
|
+ config.set("ltcproxy", "debug", DEBUG)
|
|
56
|
+ config.set("ltcproxy", "port", PORT_NUMBER)
|
|
57
|
+ config.set("ltcproxy", "redirect", REDIRECT)
|
|
58
|
+ config.set("ltcproxy", "cache", CACHE)
|
|
59
|
+ config.set("ltcproxy", "key", " ".join(KEY))
|
|
60
|
+ config.set("ltcproxy", "wsgi", SERVER)
|
|
61
|
+ config.set("ltcproxy", "workers", WORKERS)
|
|
62
|
+ config.set("ltcproxy", "ltc_user", LTC_USER)
|
|
63
|
+ config.set("ltcproxy", "ltc_password", LTC_PASSWORD)
|
|
64
|
+ config.write(open(proxy_cfg_file, "w"))
|
|
65
|
+else:
|
|
66
|
+ config.read(proxy_cfg_file)
|
|
67
|
+ DEBUG = config.getboolean("ltcproxy", "debug")
|
|
68
|
+ PORT_NUMBER = config.getint("ltcproxy", "port")
|
|
69
|
+ REDIRECT = config.getboolean("ltcproxy", "redirect")
|
|
70
|
+ CACHE = config.getboolean("ltcproxy", "cache")
|
|
71
|
+ KEY = config.get("ltcproxy", "key").split(" ")
|
|
72
|
+ SERVER = config.get("ltcproxy", "wsgi")
|
|
73
|
+ WORKERS = config.getint("ltcproxy", "workers")
|
|
74
|
+ LTC_USER = config.get("ltcproxy", "ltc_user")
|
|
75
|
+ LTC_PASSWORD = config.get("ltcproxy", "ltc_password")
|
|
76
|
+
|
|
77
|
+s = Cache(cache_dir)
|
|
78
|
+app = Bottle()
|
|
79
|
+token = None
|
|
80
|
+
|
|
81
|
+########################################################################################
|
|
82
|
+
|
|
83
|
+@app.hook('before_request')
|
|
84
|
+def set_globals():
|
|
85
|
+ global s, headers0, token
|
|
86
|
+ key = request.path.split("/")[1]
|
|
87
|
+ if not key in KEY:
|
|
88
|
+ print "Error: Wrong key - %s"% key
|
|
89
|
+ raise bottle.HTTPError(500, "Wrong key")
|
|
90
|
+ s = Cache(cache_dir)
|
|
91
|
+ if "token" in s and s["token"]:
|
|
92
|
+ token = s["token"]
|
|
93
|
+ else:
|
|
94
|
+ token = login(LTC_USER, LTC_PASSWORD)
|
|
95
|
+ if token:
|
|
96
|
+ s.set("token", token, expire=3600*24*1) # pēc 1d ekspirejas
|
|
97
|
+ print "** %s: token=%s" % (request.remote_addr,token)
|
|
98
|
+ else:
|
|
99
|
+ print "Can not login"
|
|
100
|
+ raise bottle.HTTPError(500, "Can not login")
|
|
101
|
+
|
|
102
|
+# @app.route('/playstream/<url:re:.*>')
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+### Live playlist ###
|
|
106
|
+@app.route("/<key>/live/<ch>/")
|
|
107
|
+def get_live(key, ch):
|
|
108
|
+ global s, token, headers0
|
|
109
|
+ path0, rest = hls_split(request.url)
|
|
110
|
+ response.content_type = "application/x-mpegURL" # r.headers["content-type"] # 'application/vnd.apple.mpegurl' # application/x-mpegURL
|
|
111
|
+ if "c"+ch in s:
|
|
112
|
+ stream_url2 = s["c"+ch]
|
|
113
|
+ mediaid = s["m"+ch]
|
|
114
|
+ print "** %s: serving live playlist for %s (%s) from cache" % (request.remote_addr,path0,mediaid )
|
|
115
|
+ else:
|
|
116
|
+ stream_url2, mediaid = refresh_live_chunklist_url(ch)
|
|
117
|
+ print "** %s: getting ive playlist for %s (%s)" % (request.remote_addr,path0,mediaid )
|
|
118
|
+ stream_url2 += token
|
|
119
|
+
|
|
120
|
+ if REDIRECT:
|
|
121
|
+ bottle.redirect(stream_url2, 307)
|
|
122
|
+
|
|
123
|
+ for i in range(3):
|
|
124
|
+ r2 = requests.get(stream_url2,headers=headers0)
|
|
125
|
+ if r2.status_code == 200:
|
|
126
|
+ break
|
|
127
|
+ time.sleep(1)
|
|
128
|
+ else:
|
|
129
|
+ print "Error %s getting live chunklist %s"% (r2.status_code,stream_url2)
|
|
130
|
+ raise bottle.HTTPError(r2.status_code)
|
|
131
|
+ return r2.content
|
|
132
|
+
|
|
133
|
+### Live TS chunk ###
|
|
134
|
+@app.route("/<key>/live/<ch>/<tail>")
|
|
135
|
+def get_live_chunk(key, ch, tail):
|
|
136
|
+ global s, token, headers0
|
|
137
|
+ path0, rest = hls_split(request.url)
|
|
138
|
+ chid = re.search("resource_id=c-(\\w+)",rest).group(1)
|
|
139
|
+ chunkid = re.search("(\d+)\.ts", request.url).group(1)
|
|
140
|
+ path2 = ch + "/" + chunkid
|
|
141
|
+ if CACHE and path2 in s:
|
|
142
|
+ print "** %s: serving live ts %s from cache" % (request.remote_addr,path2)
|
|
143
|
+ f = s.get(path2, read=True)
|
|
144
|
+ response.headers["Content-Type"] = s[path2+"@"] #'video/MP2T'
|
|
145
|
+ response.headers["Content-Length"] = s[path2+"#"]
|
|
146
|
+ while True:
|
|
147
|
+ chunk = f.read(8192)
|
|
148
|
+ if not chunk:
|
|
149
|
+ break
|
|
150
|
+ yield chunk
|
|
151
|
+
|
|
152
|
+ else: # no cache
|
|
153
|
+ if ch in s:
|
|
154
|
+ stream_url = s[ch]
|
|
155
|
+ mediaid= s["m"+ch]
|
|
156
|
+ else:
|
|
157
|
+ refresh_live_chunklist_url(ch)
|
|
158
|
+ if ch in s:
|
|
159
|
+ stream_url = s[ch]
|
|
160
|
+ mediaid= s["m"+ch]
|
|
161
|
+ else:
|
|
162
|
+ print "No stream_url %s in cache" % path0
|
|
163
|
+ raise bottle.HTTPError(500)
|
|
164
|
+ base0, rest0 = hls_base(stream_url)
|
|
165
|
+ rest2 = "media_%s_%s.ts?resource_id=c-%s&auth_token=app_" % (mediaid, chunkid, chid)
|
|
166
|
+ url = base0 + rest2 + token
|
|
167
|
+ url2 = hls_base(stream_url)[0] + rest
|
|
168
|
+ headers = dict(request.headers)
|
|
169
|
+ del headers["Host"]
|
|
170
|
+ # headers["Authorization"] = "Bearer " + token
|
|
171
|
+ print "** %s: getting live ts from %s(%s)- %s" % (request.remote_addr, path2, mediaid,url[:40])
|
|
172
|
+ if DEBUG:
|
|
173
|
+ print "=== Request headers ==="
|
|
174
|
+ print_headers(headers)
|
|
175
|
+ r = requests.get(url, stream=True, headers=headers0)
|
|
176
|
+ if r.status_code <> 200:
|
|
177
|
+ r = requests.get(url, stream=True, headers=headers0) # try once more
|
|
178
|
+ if r.status_code <> 200:
|
|
179
|
+ # Refresh chunklist
|
|
180
|
+ print "## %s: Refreshing chunklist/mediaid for live channel %s" %(request.remote_addr, ch)
|
|
181
|
+ chunklist_url, mediaid = refresh_live_chunklist_url(ch)
|
|
182
|
+ rest2 = "media_%s_%s.ts?resource_id=c-%s&auth_token=app_" % (mediaid, chunkid, chid)
|
|
183
|
+ url = base0 + rest2 + token
|
|
184
|
+ url2 = chunklist_url + token
|
|
185
|
+ print "** %s: getting live ts from %s(%s)- %s" % (request.remote_addr, path2, mediaid,url[:40])
|
|
186
|
+ r = requests.get(url, stream=True, headers=headers0)
|
|
187
|
+ if r.status_code <> 200:
|
|
188
|
+ print "Error %s opening stream \n%s" %(r.status_code,url)
|
|
189
|
+ print url2
|
|
190
|
+ raise bottle.HTTPError(r.status_code, "Error opening stream "+url)
|
|
191
|
+
|
|
192
|
+ content = ""
|
|
193
|
+ response.content_type = r.headers["content-type"] # 'application/vnd.apple.mpegurl' #
|
|
194
|
+ # response.headers.clear()
|
|
195
|
+ for k in r.headers:
|
|
196
|
+ response.headers[k] = r.headers[k]
|
|
197
|
+ if DEBUG:
|
|
198
|
+ print "=== Response headers ==="
|
|
199
|
+ print_headers(response.headers)
|
|
200
|
+ for chunk in r.iter_content(chunk_size=8192):
|
|
201
|
+ if chunk:
|
|
202
|
+ content += chunk
|
|
203
|
+ yield chunk
|
|
204
|
+ if len(content) <> int(r.headers["content-length"]):
|
|
205
|
+ print "Content length problem"
|
|
206
|
+ if CACHE:
|
|
207
|
+ s.set(path2, content, expire=3600, read=True)
|
|
208
|
+ s.set(path2+"#", len(content), expire=3600, read=True)
|
|
209
|
+ s.set(path2+"@", r.headers["Content-Type"], expire=3600, read=True)
|
|
210
|
+
|
|
211
|
+### Archive playlist ###
|
|
212
|
+@app.route("/<key>/live/<ch>/<ts>/")
|
|
213
|
+def get_archive(key, ch, ts):
|
|
214
|
+ global s, token, headers0
|
|
215
|
+ path0, rest = hls_split(request.url)
|
|
216
|
+ start = int(ts) + 60 * 5
|
|
217
|
+ epg = get_epg(ch, start)
|
|
218
|
+ print "** %s: getting archive playlist for channel %s" % (request.remote_addr,path0)
|
|
219
|
+ if epg:
|
|
220
|
+ epgid = epg["id"]
|
|
221
|
+ epg_start = int(epg["attributes"]["unix-start"])
|
|
222
|
+ epg_stop = int(epg["attributes"]["unix-stop"])
|
|
223
|
+ epg_title = epg["attributes"]["title"]
|
|
224
|
+ else:
|
|
225
|
+ print "EPG not found"
|
|
226
|
+ raise bottle.HTTPError(500, "EPG not found")
|
|
227
|
+
|
|
228
|
+ stream_url = epg_get_stream_url(epgid)
|
|
229
|
+ if REDIRECT:
|
|
230
|
+ bottle.redirect(stream_url, 307)
|
|
231
|
+
|
|
232
|
+ # Getting chunklist
|
|
233
|
+ stream_url2, mediaid = refresh_epg_chunklist_url(stream_url)
|
|
234
|
+ r2 = requests.get(stream_url2)
|
|
235
|
+ if r2.status_code <> 200:
|
|
236
|
+ print "Error %s getting archive chunklist %s"% (r2.status_code,stream_url2)
|
|
237
|
+ raise bottle.HTTPError(r2.status_code)
|
|
238
|
+ result = re.findall(r"#EXTINF:([\d\.]+),\n(.+)", r2.content)
|
|
239
|
+ ll = 0
|
|
240
|
+ i = 0
|
|
241
|
+ for chunk_len, chunk_url in result:
|
|
242
|
+ ll += float(chunk_len)
|
|
243
|
+ if ll > (start - epg_start):
|
|
244
|
+ break
|
|
245
|
+ i += 1
|
|
246
|
+ result2 =result[i:]
|
|
247
|
+ content = re.search("(^.+?)#EXTINF", r2.content, re.DOTALL).group(1)
|
|
248
|
+ for chunk_len, chunk_url in result2:
|
|
249
|
+ content += "#EXTINF:%s,\n" % chunk_len
|
|
250
|
+ content += chunk_url + "\n"
|
|
251
|
+ content += "#EXT-X-ENDLIST"
|
|
252
|
+ response.content_type = r2.headers["content-type"] # 'application/vnd.apple.mpegurl' #
|
|
253
|
+ return content
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+def live_get_stream_url(ch):
|
|
257
|
+ global s, token, headers0
|
|
258
|
+ if ch in s:
|
|
259
|
+ stream_url = s[ch]
|
|
260
|
+ stream_url += token
|
|
261
|
+ else:
|
|
262
|
+ # Getting live stream url
|
|
263
|
+ url = url0 + "live-streams/%s?include=quality&auth_token=app_%s" % (ch, token)
|
|
264
|
+ headers = headers0.copy()
|
|
265
|
+ headers["Authorization"] = "Bearer " + token
|
|
266
|
+ r = requests.get(url, headers=headers)
|
|
267
|
+ if r.status_code <> 200:
|
|
268
|
+ print "Error getting epg stream url "+url
|
|
269
|
+ raise bottle.HTTPError(r.status_code, "Error getting epg stream url "+url)
|
|
270
|
+ js = json.loads(r.content)
|
|
271
|
+ stream_url = js["data"][0]["attributes"]["stream-url"]
|
|
272
|
+ stream_url0 = stream_url.replace(token, "")
|
|
273
|
+ s.set(ch, stream_url0, expire=3600*24*7, read=False)
|
|
274
|
+ return str(stream_url)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+def epg_get_stream_url(epgid):
|
|
278
|
+ global s, token, headers0
|
|
279
|
+ if epgid in s:
|
|
280
|
+ stream_url = s[epgid]
|
|
281
|
+ stream_url += token
|
|
282
|
+ else:
|
|
283
|
+ # Getting epg stream url
|
|
284
|
+ url = url0 + "record-streams/%s?include=quality&auth_token=app_%s" % (epgid, token)
|
|
285
|
+ headers = headers0.copy()
|
|
286
|
+ headers["Authorization"] = "Bearer " + token
|
|
287
|
+ r = requests.get(url, headers=headers)
|
|
288
|
+ if r.status_code <> 200:
|
|
289
|
+ print "Error getting epg stream url "+url
|
|
290
|
+ raise bottle.HTTPError(r.status_code, "Error getting epg stream url "+url)
|
|
291
|
+ js = json.loads(r.content)
|
|
292
|
+ stream_url = js["data"][0]["attributes"]["stream-url"]
|
|
293
|
+ stream_url0 = stream_url.replace(token, "")
|
|
294
|
+ s.set(epgid, stream_url0, expire=3600*24*7, read=False)
|
|
295
|
+ return str(stream_url)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+def refresh_live_chunklist_url(ch):
|
|
299
|
+ global s, token, headers0
|
|
300
|
+ stream_url = live_get_stream_url(ch)
|
|
301
|
+ r = requests.get(stream_url)
|
|
302
|
+ if r.status_code <> 200:
|
|
303
|
+ print "Error %s getting live chunklist %s"% (r.status_code,stream_url)
|
|
304
|
+ raise bottle.HTTPError(r.status_code)
|
|
305
|
+ chid = re.search("resource_id=c\\-(\\w+)",stream_url).group(1)
|
|
306
|
+ rest2 = re.search("chunklist.+$", r.content).group(0).replace(token,"")
|
|
307
|
+ mediaid = re.search("chunklist_(.+?)\\.m3u8",rest2).group(1)
|
|
308
|
+ base2 = hls_base(stream_url)[0]
|
|
309
|
+ stream_url2 = base2 + rest2 # chunlist url
|
|
310
|
+ s.set("m"+ch, mediaid, expire=3600*24*7, read=False)
|
|
311
|
+ s.set("c"+ch, stream_url2, expire=3600*24*7, read=False)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+def refresh_epg_chunklist_url(stream_url):
|
|
315
|
+ global s, token, headers0
|
|
316
|
+ r = requests.get(stream_url)
|
|
317
|
+ if r.status_code <> 200:
|
|
318
|
+ print "Error %s getting archive chunklist %s"% (r.status_code,stream_url)
|
|
319
|
+ raise bottle.HTTPError(r.status_code)
|
|
320
|
+ epgid = re.search("resource_id=a-(\\d+)",stream_url).group(1)
|
|
321
|
+ rest2 = re.search("chunklist.+$", r.content).group(0)
|
|
322
|
+ mediaid = re.search("chunklist_(.+?)\\.m3u8",rest2).group(1)
|
|
323
|
+ s.set("m"+epgid, mediaid, expire=3600*24*7, read=False)
|
|
324
|
+ base2 = hls_base(stream_url)[0]
|
|
325
|
+ stream_url2 = base2 + rest2 # chunlist url
|
|
326
|
+ return stream_url2,mediaid
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+### Archive ts chunk ###
|
|
330
|
+@app.route("/<key>/live/<ch>/<ts>/<tail>")
|
|
331
|
+def get_archive_chunk(key, ch, ts, tail):
|
|
332
|
+ global s, token, headers0
|
|
333
|
+ path0, rest = hls_split(request.url)
|
|
334
|
+ epgid = re.search("resource_id=a-(\\d+)",rest).group(1)
|
|
335
|
+ chunkid = re.search("(\\d+)\\.ts", rest).group(1)
|
|
336
|
+ path2 = epgid + "/" + chunkid
|
|
337
|
+ if CACHE and path2 in s:
|
|
338
|
+ print "** %s: serving archive ts from cache %s" % (request.remote_addr,path2)
|
|
339
|
+ f = s.get(path2, read=True)
|
|
340
|
+ response.headers["Content-Type"] = s[path2+"@"] #'video/MP2T'
|
|
341
|
+ response.headers["Content-Length"] = s[path2+"#"]
|
|
342
|
+ while True:
|
|
343
|
+ chunk = f.read(8192)
|
|
344
|
+ if not chunk:
|
|
345
|
+ break
|
|
346
|
+ yield chunk
|
|
347
|
+
|
|
348
|
+ else: # No cache
|
|
349
|
+ stream_url = epg_get_stream_url(epgid)
|
|
350
|
+ if "m"+epgid in s:
|
|
351
|
+ mediaid= s["m"+epgid]
|
|
352
|
+ else:
|
|
353
|
+ chunklist_url, mediaid = refresh_epg_chunklist_url(stream_url)
|
|
354
|
+ base0, rest0 = hls_base(stream_url)
|
|
355
|
+ #media_w76603200_0.ts?resource_id=a-6559656352477&auth_token=app_
|
|
356
|
+ rest2 = "media_%s_%s.ts?resource_id=a-%s&auth_token=app_" % (mediaid, chunkid, epgid)
|
|
357
|
+ url = base0 + rest2 + token
|
|
358
|
+ print "** %s: getting archive ts from %s(%s) - %s" % (request.remote_addr,path2, mediaid, rest2[:rest2.index("?")])
|
|
359
|
+ #print url
|
|
360
|
+ headers = dict(request.headers)
|
|
361
|
+ del headers["Host"]
|
|
362
|
+ # headers["Authorization"] = "Bearer " + token
|
|
363
|
+
|
|
364
|
+ r = requests.get(url, stream=True, headers=headers)
|
|
365
|
+ if r.status_code <> 200:
|
|
366
|
+ r = requests.get(url, stream=True, headers=headers) # try once more
|
|
367
|
+ if r.status_code <> 200:
|
|
368
|
+ # Refresh chunklist
|
|
369
|
+ print "## %s: Refreshing chunklist/mediaid for epg %s" %(request.remote_addr, epgid)
|
|
370
|
+ chunklist_url, mediaid = refresh_epg_chunklist_url(stream_url)
|
|
371
|
+ rest2 = "media_%s_%s.ts?resource_id=a-%s&auth_token=app_" % (mediaid, chunkid, epgid)
|
|
372
|
+ url = base0 + rest2 + token
|
|
373
|
+ print "** %s: getting archive ts from %s(%s) - %s" % (request.remote_addr, path2, mediaid, rest2[:rest2.index("?")])
|
|
374
|
+ r = requests.get(url, stream=True, headers=headers0)
|
|
375
|
+ if r.status_code <> 200:
|
|
376
|
+ print "Error %s opening stream \n%s" %(r.status_code,url)
|
|
377
|
+ raise bottle.HTTPError(r.status_code, "Error opening stream "+url)
|
|
378
|
+
|
|
379
|
+ content = ""
|
|
380
|
+ response.content_type = r.headers["content-type"] # 'application/vnd.apple.mpegurl' #
|
|
381
|
+ # response.headers.clear()
|
|
382
|
+ for k in r.headers:
|
|
383
|
+ response.headers[k] = r.headers[k]
|
|
384
|
+ if DEBUG:
|
|
385
|
+ print_headers(response.headers)
|
|
386
|
+ for chunk in r.iter_content(chunk_size=8192):
|
|
387
|
+ if chunk:
|
|
388
|
+ content += chunk
|
|
389
|
+ yield chunk
|
|
390
|
+ if CACHE:
|
|
391
|
+ path2 = epgid + "/" + chunkid
|
|
392
|
+ s.set(path2, content, expire=3600, read=True)
|
|
393
|
+ s.set(path2+"#", len(content), expire=3600, read=True)
|
|
394
|
+ s.set(path2+"@", r.headers["Content-Type"], expire=3600, read=True)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+@app.route("/<key>/vod/<ch>/")
|
|
398
|
+def get_vod(key, ch):
|
|
399
|
+ global s, token, headers0
|
|
400
|
+ path0, rest = hls_split(request.url)
|
|
401
|
+ if path0 in s:
|
|
402
|
+ stream_url = s[path0] + token
|
|
403
|
+ print "** %s: getting vod to %s from cache (%s)" % (request.remote_addr, path0)
|
|
404
|
+ else:
|
|
405
|
+ url = url0 + "vod-streams/%s?include=language,subtitles,quality &auth_token=app_%s" % (ch, token)
|
|
406
|
+ headers = headers0.copy()
|
|
407
|
+ headers["Authorization"] = "Bearer " + token
|
|
408
|
+ r = requests.get(url, headers=headers)
|
|
409
|
+ if r.status_code <> 200:
|
|
410
|
+ raise bottle.HTTPError(r.status_code, "Error opening stream "+url)
|
|
411
|
+ js = json.loads(r.content)
|
|
412
|
+ stream_url = js["data"][0]["attributes"]["stream-url"]
|
|
413
|
+ stream_url0 = stream_url.replace(token, "")
|
|
414
|
+ s.set(path0, stream_url0, expire=3600*24*7, read=False)
|
|
415
|
+ print "** %s: changing vod to %s (%s)" % (request.remote_addr, path0)
|
|
416
|
+ if True: # REDIRECT:
|
|
417
|
+ bottle.redirect(stream_url, 307)
|
|
418
|
+ r = requests.get(stream_url)
|
|
419
|
+ if r.status_code <> 200:
|
|
420
|
+ raise bottle.HTTPError(r.status_code)
|
|
421
|
+ response.content_type = r.headers["content-type"] # 'application/vnd.apple.mpegurl' #
|
|
422
|
+ return r.content
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+def get_epg(ch, start):
|
|
426
|
+ url = url0 + "epgs/?filter[channel]=%s&filter[utFrom]=%s&filter[utTo]=%s&include=channel&page[size]=40page[number]=1" % (ch, start, start )
|
|
427
|
+ r = requests.get(url)
|
|
428
|
+ if r.status_code <> 200:
|
|
429
|
+ raise bottle.HTTPError(500, "EPG not found")
|
|
430
|
+ js = json.loads(r.content)
|
|
431
|
+ if "data" in js:
|
|
432
|
+ for epg in js["data"]:
|
|
433
|
+ if int(epg["id"]) < 0:
|
|
434
|
+ continue
|
|
435
|
+ else:
|
|
436
|
+ break
|
|
437
|
+ return epg
|
|
438
|
+ else:
|
|
439
|
+ return None
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+####################################################################
|
|
443
|
+# Run WSGI server
|
|
444
|
+def start(server,port):
|
|
445
|
+ print "*** Starting ltcproxy ***"
|
|
446
|
+ options = {}
|
|
447
|
+ if server == "mtwsgi":
|
|
448
|
+ import mtwsgi
|
|
449
|
+ server = mtwsgi.MTServer
|
|
450
|
+ options = {"thread_count": WORKERS,}
|
|
451
|
+
|
|
452
|
+ run(app=app,server=server, host='0.0.0.0',
|
|
453
|
+ port=port,
|
|
454
|
+ reloader=False,
|
|
455
|
+ quiet=False,
|
|
456
|
+ plugins=None,
|
|
457
|
+ debug=True,
|
|
458
|
+ config=None,
|
|
459
|
+ **options)
|
|
460
|
+
|
|
461
|
+def login(user,password):
|
|
462
|
+ """Login in to site, get token"""
|
|
463
|
+
|
|
464
|
+ # Dabūjam tokenu
|
|
465
|
+ url = "https://manstv.lattelecom.tv/api/v1.7/post/user/users/%s" % user
|
|
466
|
+ params = "uid=5136baee57505694&password=%s&" % (password)
|
|
467
|
+ headers = headers2dict("""
|
|
468
|
+User-Agent: Shortcut.lv v2.9.1 / Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
|
|
469
|
+Content-Type: application/x-www-form-urlencoded; charset=UTF-8
|
|
470
|
+Host: manstv.lattelecom.tv
|
|
471
|
+""" )
|
|
472
|
+ try:
|
|
473
|
+ r = urllib2.Request(url, data=params, headers=headers)
|
|
474
|
+ u = urllib2.urlopen(r)
|
|
475
|
+ content = u.read()
|
|
476
|
+ u.close()
|
|
477
|
+ except Exception as ex:
|
|
478
|
+ return None
|
|
479
|
+ if r and "token" in content:
|
|
480
|
+ token = re.search('"token":"(.+?)"', content).group(1)
|
|
481
|
+ return token
|
|
482
|
+ else:
|
|
483
|
+ return False
|
|
484
|
+
|
|
485
|
+def refresh_token(token):
|
|
486
|
+ """Refresh"""
|
|
487
|
+
|
|
488
|
+ url = "https://manstv.lattelecom.tv/api/v1.7/post/user/refresh-token/"
|
|
489
|
+ params = "uid=5136baee57505694&token=%s&" % (token)
|
|
490
|
+ headers = headers2dict("""
|
|
491
|
+User-Agent: Shortcut.lv v2.9.1 / Dalvik/1.6.0 (Linux; U; Android 4.4.2; SM-G900FD Build/KOT49H)
|
|
492
|
+Content-Type: application/x-www-form-urlencoded; charset=UTF-8
|
|
493
|
+Host: manstv.lattelecom.tv
|
|
494
|
+""" )
|
|
495
|
+ try:
|
|
496
|
+ r = urllib2.Request(url, data=params, headers=headers)
|
|
497
|
+ u = urllib2.urlopen(r)
|
|
498
|
+ content = u.read()
|
|
499
|
+ u.close()
|
|
500
|
+ except Exception as ex:
|
|
501
|
+ return None
|
|
502
|
+ if r and "token" in content:
|
|
503
|
+ token2 = re.search('"token":"(.+?)"', content).group(1)
|
|
504
|
+ return token2
|
|
505
|
+ else:
|
|
506
|
+ return False
|
|
507
|
+
|
|
508
|
+def print_headers(headers):
|
|
509
|
+ for h in headers:
|
|
510
|
+ print "%s: %s"%(h,headers[h])
|
|
511
|
+
|
|
512
|
+def del_headers(headers0,tags):
|
|
513
|
+ headers = headers0.copy()
|
|
514
|
+ for t in tags:
|
|
515
|
+ if t in headers:
|
|
516
|
+ del headers[t]
|
|
517
|
+ if t.lower() in headers:
|
|
518
|
+ del headers[t.lower()]
|
|
519
|
+ return headers
|
|
520
|
+
|
|
521
|
+def hls_split(url):
|
|
522
|
+ pp = urlparse.urlsplit(url)
|
|
523
|
+ path0 = pp.path[:pp.path.rindex("/")+1]
|
|
524
|
+ path0 = path0[path0.index("/", 1):]
|
|
525
|
+ rest = pp.path[pp.path.rindex("/")+1:] + "?" + pp.query
|
|
526
|
+ return path0, rest
|
|
527
|
+
|
|
528
|
+def hls_base(url):
|
|
529
|
+ base = url.split("?")[0]
|
|
530
|
+ base = "/".join(base.split("/")[0:-1])+ "/"
|
|
531
|
+ rest = url.replace(base, "")
|
|
532
|
+ return base, rest
|
|
533
|
+
|
|
534
|
+#########################################################################################
|
|
535
|
+if __name__ == '__main__':
|
|
536
|
+ # 1561839586
|
|
537
|
+ # get_epg("101", 1561839586)
|
|
538
|
+
|
|
539
|
+ try:
|
|
540
|
+ opts, args = getopt.gnu_getopt(sys.argv[1:], "p:s:dr", ["port=","server=","--debug"])
|
|
541
|
+ except getopt.GetoptError as err:
|
|
542
|
+ print str(err)
|
|
543
|
+ print str(__doc__)
|
|
544
|
+ sys.exit(2)
|
|
545
|
+ opts = dict(opts)
|
|
546
|
+
|
|
547
|
+ if not len(args):
|
|
548
|
+ print str(__doc__)
|
|
549
|
+ sys.exit(2)
|
|
550
|
+
|
|
551
|
+ if "-r" in opts:
|
|
552
|
+ print "Enabling remote debuging (ptvsd)"
|
|
553
|
+ import ptvsd
|
|
554
|
+ ptvsd.enable_attach(address = ('0.0.0.0', 5678),redirect_output=False)
|
|
555
|
+ if "-d" in opts:
|
|
556
|
+ print "Enabling debuging mode (more output)"
|
|
557
|
+ DEBUG = True
|
|
558
|
+ pid = "/var/run/ltcproxy.pid"
|
|
559
|
+ daemon = daemonize.Daemon(start, pid)
|
|
560
|
+ server = opts["-s"] if "-s" in opts else SERVER
|
|
561
|
+ port = opts["-p"] if "-p" in opts else PORT_NUMBER
|
|
562
|
+
|
|
563
|
+ if "start" == args[0]:
|
|
564
|
+ s.clear()
|
|
565
|
+ daemon.start(server,port)
|
|
566
|
+ daemon.is_running()
|
|
567
|
+ elif "stop" == args[0]:
|
|
568
|
+ daemon.stop()
|
|
569
|
+ elif "restart" == args[0]:
|
|
570
|
+ s.clear()
|
|
571
|
+ daemon.restart()
|
|
572
|
+ daemon.is_running()
|
|
573
|
+ elif "manualstart" == args[0]:
|
|
574
|
+ s.clear()
|
|
575
|
+ start(server,port)
|
|
576
|
+ elif "status" == args[0]:
|
|
577
|
+ daemon.is_running()
|
|
578
|
+ else:
|
|
579
|
+ print "Unknown command"
|
|
580
|
+ print str(__doc__)
|
|
581
|
+ sys.exit(2)
|
|
582
|
+ sys.exit(0)
|