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