transcoding option for web-video added
[vpproxy.git] / plugins / 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' )
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]=='m3ut':
34           prefix='mp4'  
35         else:
36           connection.dieWithError(404)  
37         
38         if len(self.splitted_path)>3:
39             connection.dieWithError()
40             return
41             
42         if len(self.splitted_path)<3:
43
44            m3u_file=config.m3u_directory+'/'+config.m3u_default
45
46         else:
47
48            if self.splitted_path[2]=='index':
49                for dir in os.walk(config.m3u_directory):
50                    if dir[0]==config.m3u_directory:
51                        text='\n'.join(dir[2])
52
53                connection.send_response(200)
54                connection.send_header('Content-Type', 'text/plain')
55                connection.end_headers()
56
57                listing = text.encode('utf-8')
58                connection.wfile.write(listing) 
59                 
60                return
61
62            m3u_file=config.m3u_directory+'/'+self.splitted_path[2]
63
64         connection.send_response(200)
65         connection.send_header('Content-Type', 'application/x-mpegurl')
66         connection.end_headers()
67
68         try:
69             playlist=parseM3U(m3u_file)
70         except:
71             connection.dieWithError(404)
72             return    
73
74         if not playlist:
75             connection.dieWithError()
76             return
77
78         playlistgen = PlaylistGenerator()
79
80         for record in playlist:
81             channel=dict()
82             channel['name']=record.title.decode('utf-8')
83             channel['url']=record.path.decode('utf-8')            
84             playlistgen.addItem(channel)
85
86         exported = playlistgen.exportm3u(hostport,prefix)
87         exported = exported.encode('utf-8')
88         connection.wfile.write(exported)
89
90     def getparam(self, key):
91         if key in self.params:
92             return self.params[key][0]
93         else:
94             return None