aboutsummaryrefslogtreecommitdiff
path: root/addons/script.recentlyadded/RecentlyAdded.py
blob: c7beff153463fbb0ef818f114b551f92c6799b24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with XBMC; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# *
# *  this file was taken from http://xbmc-addons.googlecode.com/svn/packages/scripts/RecentlyAdded.py
# *  and modified to be a XBMC Add-on under gpl2 license on 20. November 2010.
# *
# *  Thanks to:
# *
# *  Nuka for the original RecentlyAdded.py
# *
# *  ronie and Hitcher for the improvements made while in official repo
# *  
# *  Team XBMC

import xbmc
from xbmcgui import Window
from urllib import quote_plus, unquote_plus
import re
import sys
import os
import random
    
class Main:
    # grab the home window
    WINDOW = Window( 10000 )

    def _clear_properties( self ):
        # reset Totals property for visible condition
        self.WINDOW.clearProperty( "Database.Totals" )
        # we enumerate thru and clear individual properties in case other scripts set window properties
        for count in range( self.LIMIT ):
            # we clear title for visible condition
            self.WINDOW.clearProperty( "LatestMovie.%d.Title" % ( count + 1, ) )
            self.WINDOW.clearProperty( "LatestEpisode.%d.ShowTitle" % ( count + 1, ) )
            self.WINDOW.clearProperty( "LatestSong.%d.Title" % ( count + 1, ) )

    def _get_media( self, path, file ):
        # set default values
        play_path = fanart_path = thumb_path = path + file
        # we handle stack:// media special
        if ( file.startswith( "stack://" ) ):
            play_path = fanart_path = file
            thumb_path = file[ 8 : ].split( " , " )[ 0 ]
        # we handle rar:// and zip:// media special
        if ( file.startswith( "rar://" ) or file.startswith( "zip://" ) ):
            play_path = fanart_path = thumb_path = file
        # return media info
        return xbmc.getCacheThumbName( thumb_path ), xbmc.getCacheThumbName( fanart_path ), play_path

    def _parse_argv( self ):
        try:
            # parse sys.argv for params
            params = dict( arg.split( "=" ) for arg in sys.argv[ 1 ].split( "&" ) )
        except:
            # no params passed
            params = {}
        # set our preferences
        self.LIMIT = int( params.get( "limit", "5" ) )
        self.RECENT = not params.get( "partial", "" ) == "True"
        self.ALBUMS = params.get( "albums", "" ) == "True"
        self.UNPLAYED = params.get( "unplayed", "" ) == "True"
        self.TOTALS = params.get( "totals", "" ) == "True"
        self.PLAY_TRAILER = params.get( "trailer", "" ) == "True"
        self.ALARM = int( params.get( "alarm", "0" ) )
        self.RANDOM_ORDER = params.get( "random", "" ) == "True"
    
    def _set_alarm( self ):
        # only run if user/skinner preference
        if ( not self.ALARM ): return
        # set the alarms command
        command = "XBMC.RunScript(%s,limit=%d&partial=%s&albums=%s&unplayed=%s&totals=%s&trailer=%s&alarm=%d)" % ( os.path.join( os.getcwd(), __file__ ), self.LIMIT, str( not self.RECENT ), str( self.ALBUMS ), str( self.UNPLAYED ), str( self.TOTALS ), str( self.PLAY_TRAILER ), self.ALARM, )
        xbmc.executebuiltin( "AlarmClock(LatestAdded,%s,%d,true)" % ( command, self.ALARM, ) )

    def __init__( self ):
        # parse argv for any preferences
        self._parse_argv()
        # clear properties
        self._clear_properties()
        # set any alarm
        self._set_alarm()
        # format our records start and end
        xbmc.executehttpapi( "SetResponseFormat()" )
        xbmc.executehttpapi( "SetResponseFormat(OpenRecord,%s)" % ( "<record>", ) )
        xbmc.executehttpapi( "SetResponseFormat(CloseRecord,%s)" % ( "</record>", ) )
        # fetch media info
        self._fetch_totals()
        self._fetch_movie_info()
        self._fetch_tvshow_info()
        self._fetch_music_info()

    def _fetch_totals( self ):
        # only run if user/skinner preference
        if ( not self.TOTALS ): return
        import datetime
        # get our regions format
        date_format = xbmc.getRegion( "dateshort" ).replace( "MM", "%m" ).replace( "DD", "%d" ).replace( "YYYYY", "%Y" ).replace( "YYYY", "%Y" ).strip()
        # only need to make Totals not empty
        self.WINDOW.setProperty( "Database.Totals", "true" )
        # sql statement for movie totals
        sql_totals = "select count(1), count(playCount), movieview.* from movieview group by lastPlayed"
        totals_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_totals ), )
        records = re.findall( "<record>(.+?)</record>", totals_xml, re.DOTALL )
        # initialize our list
        movies_totals = [ 0 ] * 7
        # enumerate thru and total our numbers
        for record in records:
            fields = re.findall( "<field>(.*?)</field>", record, re.DOTALL )
            movies_totals[ 0 ] += int( fields[ 0 ] )
            movies_totals[ 1 ] += int( fields[ 1 ] )
            if ( fields[ 29 ] ):
                movies_totals[ 2 ] = fields[ 3 ] # title
                movies_totals[ 3 ] = fields[ 10 ] # year
                movies_totals[ 4 ] = fields[ 14 ] # runningtime
                movies_totals[ 5 ] = fields[ 17 ] # genre
                movies_totals[ 6 ] = "" # last watched
                date = fields[ 29 ].split( " " )[ 0 ].split( "-" )
                movies_totals[ 6 ] = datetime.date( int( date[ 0 ] ), int( date[ 1 ] ), int( date[ 2 ] ) ).strftime( date_format ) # last played
        # sql statement for music videos totals
        sql_totals = "select count(1), count(playCount) from musicvideoview"
        totals_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_totals ), )
        mvideos_totals = re.findall( "<field>(.+?)</field>", totals_xml, re.DOTALL )
        # sql statement for tv shows/episodes totals
        sql_totals = "SELECT tvshow.*, path.strPath AS strPath, counts.totalcount AS totalCount, counts.watchedcount AS watchedCount, counts.totalcount=counts.watchedcount AS watched FROM tvshow JOIN tvshowlinkpath ON tvshow.idShow=tvshowlinkpath.idShow JOIN path ON path.idpath=tvshowlinkpath.idPath LEFT OUTER join (SELECT tvshow.idShow AS idShow, count(1) AS totalCount, count(files.playCount) AS watchedCount FROM tvshow JOIN tvshowlinkepisode ON tvshow.idShow=tvshowlinkepisode.idShow JOIN episode ON episode.idEpisode=tvshowlinkepisode.idEpisode JOIN files ON files.idFile=episode.idFile GROUP BY tvshow.idShow) counts ON tvshow.idShow=counts.idShow"
        totals_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_totals ), )
        # initialize our list
        tvshows_totals = [ 0 ] * 4
        records = re.findall( "<record>(.+?)</record>", totals_xml, re.DOTALL )
        # enumerate thru and total our numbers
        for record in records:
            fields = re.findall( "<field>(.*?)</field>", record, re.DOTALL )
            if ( fields[ 25 ] ):
                tvshows_totals[ 0 ] += 1
                tvshows_totals[ 1 ] += int( fields[ 24 ] ) # number of episodes
                tvshows_totals[ 2 ] += int( fields[ 26 ] ) # watched?
                tvshows_totals[ 3 ] += int( fields[ 25 ] ) # number of episodes watched
         # sql statement for tv albums/songs totals

        sql_totals = "select count(1), count(distinct strAlbum), count(distinct strArtist) from songview"
        totals_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_totals ), )
        music_totals = re.findall( "<field>(.+?)</field>", totals_xml, re.DOTALL )
        
        # set properties
        self.WINDOW.setProperty( "Movies.Count" , str( movies_totals[ 0 ] ) or "" )
        self.WINDOW.setProperty( "Movies.Watched" , str( movies_totals[ 1 ] ) or "" )
        self.WINDOW.setProperty( "Movies.UnWatched" , str( movies_totals[ 0 ] - movies_totals[ 1 ] ) or "" )
        self.WINDOW.setProperty( "Movies.LastWatchedTitle" , movies_totals[ 2 ] or "" )
        self.WINDOW.setProperty( "Movies.LastWatchedYear" , movies_totals[ 3 ] or "" )
        self.WINDOW.setProperty( "Movies.LastWatchedRuntime" , movies_totals[ 4 ] or "" )
        self.WINDOW.setProperty( "Movies.LastWatchedGenre" , movies_totals[ 5 ] or "" )
        self.WINDOW.setProperty( "Movies.LastWatchedDate" , movies_totals[ 6 ] or "" )
        
        self.WINDOW.setProperty( "MusicVideos.Count" , mvideos_totals[ 0 ] or "" )
        self.WINDOW.setProperty( "MusicVideos.Watched" , mvideos_totals[ 1 ] or "" )
        self.WINDOW.setProperty( "MusicVideos.UnWatched" , str( int( mvideos_totals[ 0 ] ) - int( mvideos_totals[ 1 ] ) ) or "" )
        
        self.WINDOW.setProperty( "TVShows.Count" , str( tvshows_totals[ 0 ] ) or "" )
        self.WINDOW.setProperty( "TVShows.Watched" , str( tvshows_totals[ 2 ] ) or "" )
        self.WINDOW.setProperty( "TVShows.UnWatched" , str( tvshows_totals[ 0 ] - tvshows_totals[ 2 ] ) or "" )
        self.WINDOW.setProperty( "Episodes.Count" , str( tvshows_totals[ 1 ] ) or "" )
        self.WINDOW.setProperty( "Episodes.Watched" , str( tvshows_totals[ 3 ] ) or "" )
        self.WINDOW.setProperty( "Episodes.UnWatched" , str( tvshows_totals[ 1 ] - tvshows_totals[ 3 ] ) or "" )
        
        self.WINDOW.setProperty( "Music.SongsCount" , music_totals[ 0 ] or "" )
        self.WINDOW.setProperty( "Music.AlbumsCount" , music_totals[ 1 ] or "" )
        self.WINDOW.setProperty( "Music.ArtistsCount" , music_totals[ 2 ] or "" )

    def _fetch_movie_info( self ):
        # set our unplayed query
        unplayed = ( "", "where playCount is null ", )[ self.UNPLAYED ]
        # sql statement
        if ( self.RANDOM_ORDER ):
            # random order
            sql_movies = "select * from movieview %sorder by RANDOM() limit %d" % ( unplayed, self.LIMIT, )        
        elif ( self.RECENT ):
            # recently added
            sql_movies = "select * from movieview %sorder by idMovie desc limit %d" % ( unplayed, self.LIMIT, )
        else:
            # movies not finished
            sql_movies = "select movieview.*, bookmark.timeInSeconds from movieview join bookmark on (movieview.idFile = bookmark.idFile) %sorder by movieview.c00 limit %d" % ( unplayed, self.LIMIT, )
        # query the database
        movies_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_movies ), )
        # separate the records
        movies = re.findall( "<record>(.+?)</record>", movies_xml, re.DOTALL )
        # enumerate thru our records and set our properties
        for count, movie in enumerate( movies ):
            # separate individual fields
            fields = re.findall( "<field>(.*?)</field>", movie, re.DOTALL )
            # set properties

            self.WINDOW.setProperty( "LatestMovie.%d.Title" % ( count + 1, ), fields[ 2 ] )
            self.WINDOW.setProperty( "LatestMovie.%d.Rating" % ( count + 1, ), fields[ 7 ] )
            self.WINDOW.setProperty( "LatestMovie.%d.Year" % ( count + 1, ), fields[ 9 ] )
            self.WINDOW.setProperty( "LatestMovie.%d.Plot" % ( count + 1, ), fields[ 3 ] )
            self.WINDOW.setProperty( "LatestMovie.%d.RunningTime" % ( count + 1, ), fields[ 13 ] )
            # get cache names of path to use for thumbnail/fanart and play path
            thumb_cache, fanart_cache, play_path = self._get_media( fields[ 25 ], fields[ 24 ] )
            if os.path.isfile("%s.dds" % (xbmc.translatePath( "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", os.path.splitext(fanart_cache)[0],) ) )):
                fanart_cache = "%s.dds" % (os.path.splitext(fanart_cache)[0],)
            self.WINDOW.setProperty( "LatestMovie.%d.Path" % ( count + 1, ), ( play_path, fields[ 21 ], )[ fields[ 21 ] != "" and self.PLAY_TRAILER ] )
            self.WINDOW.setProperty( "LatestMovie.%d.Trailer" % ( count + 1, ), fields[ 21 ] )
            self.WINDOW.setProperty( "LatestMovie.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", fanart_cache, ) )
            # initial thumb path
            thumb = "special://profile/Thumbnails/Video/%s/%s" % ( thumb_cache[ 0 ], thumb_cache, )
            # if thumb does not exist use an auto generated thumb path
            if ( not os.path.isfile( xbmc.translatePath( thumb ) ) ):
                thumb = "special://profile/Thumbnails/Video/%s/auto-%s" % ( thumb_cache[ 0 ], thumb_cache, )
            self.WINDOW.setProperty( "LatestMovie.%d.Thumb" % ( count + 1, ), thumb )

    def _fetch_tvshow_info( self ):
        # set our unplayed query
        unplayed = ( "", "where playCount is null ", )[ self.UNPLAYED ]
        # sql statement
        if ( self.RANDOM_ORDER ):
            # random order
            sql_episodes = "select * from episodeview %sorder by RANDOM() limit %d" % ( unplayed, self.LIMIT, )
        elif ( self.RECENT ):
            # recently added
            sql_episodes = "select * from episodeview %sorder by idepisode desc limit %d" % ( unplayed, self.LIMIT, )
        else:
            # tv shows not finished
            sql_episodes = "select episodeview.*, bookmark.timeInSeconds from episodeview join bookmark on (episodeview.idFile = bookmark.idFile) %sorder by episodeview.strTitle limit %d" % ( unplayed, self.LIMIT, )
        # query the database
        episodes_xml = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus( sql_episodes ), )
        # separate the records
        episodes = re.findall( "<record>(.+?)</record>", episodes_xml, re.DOTALL )
        # enumerate thru our records and set our properties
        for count, episode in enumerate( episodes ):
            # separate individual fields
            fields = re.findall( "<field>(.*?)</field>", episode, re.DOTALL )
            # set properties        
            self.WINDOW.setProperty( "LatestEpisode.%d.ShowTitle" % ( count + 1, ), fields[ 28 ] )
            self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeTitle" % ( count + 1, ), fields[ 2 ] )
            self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeNo" % ( count + 1, ), "s%02de%02d" % ( int( fields[ 14 ] ), int( fields[ 15 ] ), ) )
            self.WINDOW.setProperty( "LatestEpisode.%d.Rating" % ( count + 1, ), fields[ 5 ] )
            self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeSeason" % ( count + 1, ), fields[ 14 ] )
            self.WINDOW.setProperty( "LatestEpisode.%d.EpisodeNumber" % ( count + 1, ), fields[ 15 ] )
            self.WINDOW.setProperty( "LatestEpisode.%d.Plot" % ( count + 1, ), fields[ 3 ] )
            # get cache names of path to use for thumbnail/fanart and play path
            thumb_cache, fanart_cache, play_path = self._get_media( fields[ 25 ], fields[ 24 ] )
            if ( not os.path.isfile( xbmc.translatePath( "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", fanart_cache, ) ) ) ):
                fanart_cache = xbmc.getCacheThumbName(os.path.join(os.path.split(os.path.split(fields[ 25 ])[0])[0], ""))
            if os.path.isfile("%s.dds" % (xbmc.translatePath( "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", os.path.splitext(fanart_cache)[0],) ) )):
                fanart_cache = "%s.dds" % (os.path.splitext(fanart_cache)[0],)
            self.WINDOW.setProperty( "LatestEpisode.%d.Path" % ( count + 1, ), play_path )
            self.WINDOW.setProperty( "LatestEpisode.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Video/%s/%s" % ( "Fanart", fanart_cache, ) )
            # initial thumb path
            thumb = "special://profile/Thumbnails/Video/%s/%s" % ( thumb_cache[ 0 ], thumb_cache, )
            # if thumb does not exist use an auto generated thumb path
            if ( not os.path.isfile( xbmc.translatePath( thumb ) ) ):
                thumb = "special://profile/Thumbnails/Video/%s/auto-%s" % ( thumb_cache[ 0 ], thumb_cache, )
            self.WINDOW.setProperty( "LatestEpisode.%d.Thumb" % ( count + 1, ), thumb )

    def _fetch_music_info( self ):
        # sql statement
        if ( self.ALBUMS ):
            sql_music = "select idAlbum from albumview order by idAlbum desc limit %d" % ( self.LIMIT, )
            # query the database for recently added albums
            music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), )
            # separate the records
            albums = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL )
            # set our unplayed query
            unplayed = ( "(idAlbum = %s)", "(idAlbum = %s and lastplayed is null)", )[ self.UNPLAYED ]
            # sql statement
            sql_music = "select songview.* from songview where %s limit 1" % ( unplayed, )
            # clear our xml data
            music_xml = ""
            # enumerate thru albums and fetch info
            for album in albums:
                # query the database and add result to our string
                music_xml += xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music % ( album.replace( "<field>", "" ).replace( "</field>", "" ), ) ), )
        else:
            # set our unplayed query
            unplayed = ( "", "where lastplayed is null ", )[ self.UNPLAYED ]
            # sql statement
            sql_music = "select * from songview %sorder by idSong desc limit %d" % ( unplayed, self.LIMIT, )
            # query the database
            music_xml = xbmc.executehttpapi( "QueryMusicDatabase(%s)" % quote_plus( sql_music ), )
        # separate the records
        items = re.findall( "<record>(.+?)</record>", music_xml, re.DOTALL )
        # enumerate thru our records and set our properties
        for count, item in enumerate( items ):
            # separate individual fields
            fields = re.findall( "<field>(.*?)</field>", item, re.DOTALL )
            # set properties
            self.WINDOW.setProperty( "LatestSong.%d.Title" % ( count + 1, ), fields[ 3 ] )
            self.WINDOW.setProperty( "LatestSong.%d.Year" % ( count + 1, ), fields[ 6 ] )
            self.WINDOW.setProperty( "LatestSong.%d.Artist" % ( count + 1, ), fields[ 24 ] )
            self.WINDOW.setProperty( "LatestSong.%d.Album" % ( count + 1, ), fields[ 21 ] )
            self.WINDOW.setProperty( "LatestSong.%d.Rating" % ( count + 1, ), fields[ 18 ] )
            path = fields[ 22 ]
            # don't add song for albums list TODO: figure out how toplay albums
            ##if ( not self.ALBUMS ):
            path += fields[ 8 ]
            self.WINDOW.setProperty( "LatestSong.%d.Path" % ( count + 1, ), path )
            # get cache name of path to use for fanart
            cache_name = xbmc.getCacheThumbName( fields[ 24 ] )
            self.WINDOW.setProperty( "LatestSong.%d.Fanart" % ( count + 1, ), "special://profile/Thumbnails/Music/%s/%s" % ( "Fanart", cache_name, ) )
            self.WINDOW.setProperty( "LatestSong.%d.Thumb" % ( count + 1, ), fields[ 27 ] )


if ( __name__ == "__main__" ):
    Main()