~registry/hyberia/0.4

« back to all changes in this revision

Viewing changes to hyberia/playlist.py

  • Committer: Martin Samson
  • Date: 2010-10-02 19:55:09 UTC
  • mfrom: (59.1.1 hyb-dev)
  • Revision ID: pyrolian@gmail.com-20101002195509-8zxjow90426cl3iv
Merges

Show diffs side-by-side

added added

removed removed

Lines of Context:
46
46
        # Instanciate the logger
47
47
        self.logger = logging.getLogger("hyberia.playlist.Playlist")
48
48
        self.logger.info("Creating instance")
49
 
        
 
49
 
50
50
        if videoInfoBackend == None:
51
51
            print ("CRITICAL: HVIB not set")
52
52
            print("")
53
53
            raise PlayListVIBNotSetException()
54
 
        
 
54
 
55
55
        #Look for HVIB_API_VERSION attr
56
56
        try:
57
57
            getattr(videoInfoBackend, "HVIB_API_VERSION")
59
59
            print ("CRITICAL: Non-HVIB compliant videoInfoBackend.")
60
60
            print("")
61
61
            raise PlayListVIBNotSetException()
62
 
        
 
62
 
63
63
        #Verify it matches required version
64
64
        if not videoInfoBackend.HVIB_API_VERSION >= 1:
65
65
            print ("CRITICAL: Incompatible HVIB")
66
66
            print("")
67
67
            raise PlayListVIBNotSetException()
68
 
            
 
68
 
69
69
        self.__videoInfoBackend = videoInfoBackend
70
70
        self._playList = []
71
71
        self._blocks = {}
72
 
        
 
72
 
73
73
    def __createBlock(self, id = 0, runDate = 0, runTime = 0, name = "DefaultBlockName" , description = ""):
74
74
        block = {}
75
75
        block['id'] = id
80
80
        block['description'] = description
81
81
        block['parts'] = []
82
82
        return block
83
 
    
84
 
    def __createPart(self, resource):          
 
83
 
 
84
    def __createPart(self, resource):
85
85
        part = {}
86
 
        
 
86
 
87
87
        #The video file name
88
88
        part['file'] = resource['file']
89
89
        part['name'] = resource['name']
90
 
        
 
90
 
91
91
        #Duration in seconds
92
92
        part['duration'] = self.__videoInfoBackend.HVIB_RunningTime(part['file'])
93
 
        
 
93
 
94
94
        #Will hold when to play the file as a datetime format (yyyymmddhhiiss)
95
95
        part['playAt'] = 0
96
96
        return part
97
 
    
 
97
 
98
98
    def load(self, playListFile):
99
99
        '''Load the playlist file into memory'''
100
 
        
101
 
        
 
100
 
 
101
        # Get the playlist file
 
102
        playListFile = playListFile + "/playlist.json"
 
103
        self.logger.debug("Loading playlist from %s" % (playListFile,))
 
104
 
102
105
        #Verify the playlist file exists
103
106
        if not os.path.exists(playListFile):
104
107
            self.logger.critical("Playlist file not found.");
105
108
            raise PlayListNotFoundException()
106
 
        
 
109
 
107
110
        #Attempt to parse the playlist file
108
111
        try:
109
112
            playListStruct = json.load(open(playListFile, "r"))
111
114
            print(e)
112
115
            print("This is a parsing error. Strings in json must be delimited with \" instead of ' ")
113
116
            raise PlayListImportErrorException()
114
 
        
 
117
 
115
118
        #Verify that some data exists
116
119
        for elem in ["blocks","resources"]:
117
120
            if not elem in playListStruct:
118
121
                print(elem + " not found")
119
122
                raise PlayListImportErrorException()
120
123
 
121
 
        
 
124
 
122
125
        #Parse the resources
123
126
        for resource in playListStruct['resources']:
124
127
            if not 'file' in playListStruct['resources'][resource]:
125
128
                print("CRITICAL: Resource "+ str(resource) +" has no file attribute");
126
129
                raise PlayListImportErrorException()
127
 
            
 
130
 
128
131
            if not 'file' in playListStruct['resources'][resource]:
129
132
                print("CRITICAL: Resource "+ resource +" does not have a file attribute!")
130
133
                raise PlayListImportErrorException()
131
 
                
 
134
 
132
135
            if not os.path.exists(playListStruct['resources'][resource]['file']):
133
136
                print("CRITICAL: Resource " + str(resource) + " file ("+ playListStruct['resources'][resource]['file'] +") does not exists")
134
137
                raise PlayListImportErrorException()
135
 
                
136
 
                
137
 
                
 
138
 
 
139
 
 
140
 
138
141
        for dateBlock in playListStruct["blocks"]:
139
 
            
 
142
 
140
143
            prev_block_id = 0
141
 
            
 
144
 
142
145
            for timeBlock in playListStruct["blocks"][dateBlock]:
143
146
                blockStruct = playListStruct["blocks"][dateBlock][timeBlock]
144
 
                
 
147
 
145
148
                if len(blockStruct['parts']) == 0:
146
149
                    print("WARNING: Skipping block " + str(timeBlock) + " on " + str(dateBlock) + ". No parts to play")
147
150
                    continue
148
 
                
 
151
 
149
152
                for item in ['name','description', 'parts']:
150
153
                    if not item in blockStruct:
151
154
                        print ("CRITICAL: Block " + timeBlock +" on " + dateBlock +" does not have a " + item + "!")
152
155
                        raise PlayListImportErrorException()
153
 
                
154
 
                
 
156
 
 
157
 
155
158
                #blockid is date with seconds, move to unix timestamp
156
159
                blockId = ((int(dateBlock) * 10000) + int(timeBlock)) * 100
157
160
                blockId = datetime.datetime.strptime(str(blockId), "%Y%m%d%H%M%S")
158
161
                blockId = int(time.mktime(blockId.timetuple()))
159
 
                
 
162
 
160
163
                block = self.__createBlock(blockId,dateBlock,timeBlock,blockStruct["name"],blockStruct["description"])
161
164
                for part in blockStruct['parts']:
162
 
                    
 
165
 
163
166
                    if not part in playListStruct['resources']:
164
167
                        print("CRITICAL: Part " + str(part) + " has no resource file!")
165
168
                        raise PlayListImportErrorException()
166
 
                    
 
169
 
167
170
                    resource = playListStruct['resources'][part]
168
171
                    part = self.__createPart(resource)
169
172
 
170
 
                    part['playAt'] = blockId + block['totalRunTime']                    
 
173
                    part['playAt'] = blockId + block['totalRunTime']
171
174
                    block['parts'].append(part)
172
175
                    block['totalRunTime'] += part['duration']
173
 
                
 
176
 
174
177
                if prev_block_id > blockId:
175
178
                    print("Critical: Block duration overlapping at " + str(blockId))
176
179
                    raise PlayListImportErrorException()
177
 
                    
 
180
 
178
181
                self._playList.append(blockId)
179
182
                self._blocks[blockId] = block
180
 
                
181
 
        print ("INFO: Loaded " + str(len(self._playList)) + " blocks.")        
 
183
 
 
184
        print ("INFO: Loaded " + str(len(self._playList)) + " blocks.")
182
185
        self._playList.sort()
183
 
        
 
186
 
184
187
    def getCurrentBlock(self):
185
188
        curTimeId = int(time.time())
186
189
        curBlock = None
187
 
        
 
190
 
188
191
        for blockId in self._playList:
189
192
            if blockId < curTimeId:
190
193
                curBlock = blockId
191
194
                continue
192
 
            
 
195
 
193
196
            if not curBlock:
194
197
                curBlock = blockId
195
 
            return self._blocks[curBlock]            
 
198
            return self._blocks[curBlock]
196
199
        return None
197
200
 
198
201
if __name__ == "__main__":