Добавлена обработка заголовков запроса X-Forwarded...
[vpproxy.git] / m3u_plugin.py
1 __author__ = 'rvb'
2 '''
3 Local Playlist Plugin
4 (based on ytv plugin by ValdikSS)
5 http://ip:port/m3u
6 http://ip:port/m3u/index
7 http://ip:port/m3u{/list-name}
8 '''
9 import json
10 import logging
11 import urlparse
12 from modules.PluginInterface import VPProxyPlugin
13 from modules.PlaylistGenerator import PlaylistGenerator
14 from modules.M3uParser import parseM3U
15 import config.m3u as config
16 import os
17
18 class M3u(VPProxyPlugin):
19
20     handlers = ('m3u', 'm3ut', 'm3uw')
21
22     logger = logging.getLogger('plugin_m3u')
23     playlist = None
24
25     def handle(self, connection):
26
27         hostport = connection.headers['Host']
28
29         self.splitted_path=connection.path.split('/')
30         
31         if self.splitted_path[1]=='m3u':
32           prefix='get'
33         elif self.splitted_path[1]=='m3uw':
34           prefix='webm'  
35         elif self.splitted_path[1]=='m3ut':
36           prefix='mp4'  
37         else:
38           connection.dieWithError(404)  
39         
40         if len(self.splitted_path)>3:
41             connection.dieWithError()
42             return
43             
44         if len(self.splitted_path)<3:
45
46            m3u_file=config.m3u_directory+'/'+config.m3u_default
47
48         else:
49
50            if self.splitted_path[2]=='index':
51                for dir in os.walk(config.m3u_directory):
52                    if dir[0]==config.m3u_directory:
53                        text='\n'.join(dir[2])
54
55                connection.send_response(200)
56                connection.send_header('Content-Type', 'text/plain')
57                connection.end_headers()
58
59                listing = text.encode('utf-8')
60                connection.wfile.write(listing) 
61                 
62                return
63
64            m3u_file=config.m3u_directory+'/'+self.splitted_path[2]
65
66         connection.send_response(200)
67         connection.send_header('Content-Type', 'application/x-mpegurl')
68         connection.end_headers()
69
70         try:
71             playlist=parseM3U(m3u_file)
72         except:
73             connection.dieWithError(404)
74             return    
75
76         if not playlist:
77             connection.dieWithError()
78             return
79
80         playlistgen = PlaylistGenerator()
81
82         for record in playlist:
83             channel=dict()
84             channel['name']=record.title.decode('utf-8')
85             channel['url']=record.path.decode('utf-8')            
86             playlistgen.addItem(channel)
87
88         exported = playlistgen.exportm3u(hostport,prefix)
89         exported = exported.encode('utf-8')
90         connection.wfile.write(exported)
91
92     def getparam(self, key):
93         if key in self.params:
94             return self.params[key][0]
95         else:
96             return None