summaryrefslogtreecommitdiff
path: root/default.py
blob: 95779a704ea2c9c1d2295358debba6523b66eca5 (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
# -*- coding: UTF-8 -*-
""" Kan Video plugin """

# Copyright (c) 2017 Tzafrir Cohen
# SPDX-License-Identifier: GPL-2.0+
#
# License-Filename: LICENSE

from bs4 import BeautifulSoup
import datetime
import re
import sys
import urllib
#import urllib2
import requests
import simplecache
import threading
import urlparse
import xbmc
import xbmcgui
import xbmcplugin
import zlib


KAN_URL = 'http://www.kan.org.il'
USER_AGENT = 'Kodi/plugin.video.kan/1.0'    # I'm optimistic
PLUGIN_NAME = "plugin.video.kan"    # FIXME: a better way to get this?

class DummyCache:
    def __init__(self):
        pass

    def get(self, cache_id, checksum=''):
        return None

    def set(self, cache_id, data, checksum='', expiration=None):
        pass


SiteCache = simplecache.SimpleCache()   # FIXME: avoid this global
#SiteCache = DummyCache()        # Avoid caching for now

def trace(msg):
    xbmc.log(msg="Tzafrir: " + msg, level=xbmc.LOGNOTICE)


class Page:
    def __init__(self, argv):
        self.base_url = argv[0]
        self.addon_handle = int(argv[1])
        self.args = urlparse.parse_qs(argv[2][1:])
        self.mode = self.args.get('mode', None)
        content_type = self.args.get('content_type', None)
        if content_type:
            self.content_type = content_type[0]
        else:
            self.content_type = None

    def is_video(self):
        return self.content_type == 'video'

    def is_audio(self):
        return self.content_type == 'audio'

    def build_url(self, query):
        #query['addon_handle'] = self.addon_handle
        return self.base_url + '?' + urllib.urlencode(query)

    def add_directory_item(self, **kwargs):
        xbmcplugin.addDirectoryItem(handle=self.addon_handle, **kwargs)

    def end_directory(self):
        xbmcplugin.endOfDirectory(self.addon_handle)

    def placeholder_folder(self, foldername):
        """ A folder with a single dummy item """
        url = 'http://localhost/some_video.mkv'
        li = xbmcgui.ListItem(foldername + 'Not Implemented',
                              iconImage='DefaultVideo.png')
        self.add_directory_item(url=url, listitem=li)
        self.end_directory()

    def placeholder_item(self, name, label):
        """ An item that calls a placeholder folder """
        url = self.build_url({'mode': 'placeholder', 'name': name})
        li = xbmcgui.ListItem(label)
        self.add_directory_item(url=url, listitem=li, isFolder=True)

    def __str__(self):
        return "[base_url: {}, addon_handle: {}, mode: {}, content_type: {}]" \
               .format(self.base_url, self.addon_handle, self.mode,
                       self.content_type)

    def build_page(self, page_list, isFolder=False, isPlayable=False):
        """ Creates a complete page from a list of items (title, url) """
        for item in page_list:
            title, url = item
            li = xbmcgui.ListItem(title)
            if isPlayable:
                li.setProperty('IsPlayable','true')
            self.add_directory_item(url=url, listitem=li, isFolder=isFolder)
        self.end_directory()


def read_url(url):
    headers = {'user-agent': USER_AGENT}
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        raise IOError("Invalid URL {}".format(url))

    return response.text


def get_show_info(base_url, path):
    url = base_url + '/' + path
    page = read_url(url)
    parsed = BeautifulSoup(page, "html.parser")
    title = parsed.title.string
    title = re.sub('[|-].*', '', title)
    desc_div = parsed.find('div', class_='program_top_txt')
    desc = desc_div.text
    return (title, desc)


def title_checksum(title):
    """ A simple checksum to see that the title did not change

    Should only be good enough for the case that pages got renumbered
    and the title no longer matches page number.
    """
    return zlib.adler32(title.encode('utf-8'))


def get_program_item(res_array, page, a, i):
    """ A thread worker to get information about a program page

    input: a: the a element from the program's page.

    Writes results to the specified index in the results array.
    """
    path = a.get('href')
    show_id = re.sub('.*=', '', path)
    title, desc = get_show_info(KAN_URL, path)
    checksum = title_checksum(title)
    url = page.build_url({'mode': 'show', 'id': show_id,
                          'checksum': str(checksum)})
    res_array[i] = (title, url)


def video_top_menu(page, name):
    """ Display a menu of all the TV shows """
    trace("Show top menu for " + name)
    cache_id = PLUGIN_NAME + '.toppage.' + name
    cached_items = SiteCache.get(cache_id)
    if cached_items:
        page.build_page(cached_items, isFolder=True)
        return

    trace("Show top menu for " + name + ": no cached copy")
    tvshows_url = KAN_URL + "/video/{}.aspx".format(name)
    main_page = read_url(tvshows_url)
    parsed = BeautifulSoup(main_page, "html.parser")
    anchors = parsed.find_all('a',
                              class_="program_category_link w-inline-block")
    trace("got anchors: " + str(len(anchors)))
    page_items = [None for item in anchors]
    threads = []
    for i in range(0, len(anchors)):
        t = threading.Thread(target=get_program_item,
                             args=(page_items, page, anchors[i], i))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()
        # FIXME: check if result is still None. If so: handle error?

    page.build_page(page_items, isFolder=True)
    SiteCache.set(cache_id, page_items, expiration=datetime.timedelta(days=1))


def show_menu(page):
    """ Display a menu of items in a specific show """
    show_id = page.args['id'][0]
    checksum = page.args['checksum'][0]
    cache_id = PLUGIN_NAME + '.progpage.' + show_id
    cached_items = SiteCache.get(cache_id, checksum=checksum)
    if cached_items:
        page.build_page(cached_items, isPlayable=True)
        return

    show_url = KAN_URL + '/Program/?catId=' + show_id
    trace("URL for show {}: {}".format(show_id, show_url))

    show_page = read_url(show_url)
    parsed = BeautifulSoup(show_page, "html.parser")
    items = parsed.find_all('li',
                              class_="program_list_item w-clearfix")
    trace("got items: " + str(len(items)))
    page_items = []
    for item in items:
        titles = item.find_all('h2')
        title = titles[0].string
        iframe = item.find_all('iframe')[0]
        youtube_url = iframe['src']
        youtube_id = re.sub('.*/embed/([0-9A-Za-z]+)(\?.*)?', r'\1', youtube_url)
        trace("Add link for ID {} ({}).".format(youtube_id, title.encode('utf-8')))
        url = 'plugin://plugin.video.youtube/play/?video_id={}'.format(youtube_id)
        page_items.append((title, url))
    page.build_page(page_items, isFolder=True)
    SiteCache.set(cache_id, page_items, checksum=checksum,
                  expiration=datetime.timedelta(days=1))


def video_main_page(page):
    url = page.build_url({'mode': 'shows', 'name': 'programs'})
    li = xbmcgui.ListItem(u'תוכניות טלוויזיה')
    page.add_directory_item(url=url, listitem=li, isFolder=True)

    url = page.build_url({'mode': 'shows', 'name': 'digital'})
    li = xbmcgui.ListItem(u'תוכניות רשת')
    page.add_directory_item(url=url, listitem=li, isFolder=True)

    page.placeholder_item('new-items', u'קטעים חדשים')

    page.end_directory()


def video_main(page):
    if page.mode is not None:
        mode = page.mode[0]

    if page.mode is None:
        video_main_page(page)
    elif mode == 'shows':
        video_top_menu(page, page.args['name'][0])
    elif mode == 'show':
        show_menu(page)
    elif mode == 'placeholder':
        name = page.args['name'][0]
        page.placeholder_folder(name)
    else:
        trace("No handler for mode '{}'".format(mode))


def audio_main(page):
    if page.mode is not None:
        mode = page.mode[0]

    if page.mode is None:
        audio_main_page(page)
    elif mode == 'shows':
        video_top_menu(page, page.args['name'][0])
    elif mode == 'show':
        show_menu(page)
    elif mode == 'placeholder':
        name = page.args['name'][0]
        page.placeholder_folder(name)
    else:
        trace("No handler for mode '{}'".format(mode))


def main():
    trace(' | '.join(sys.argv))
    page = Page(sys.argv)

    trace("{}".format(page))
    trace("Video? " + str(page.is_video()) + ", audio? " + str(page.is_audio()))

    if page.is_audio():
        page.placeholder_folder("audio")
    elif page.is_video():
        video_main(page)
    else:
        page.placeholder_folder("no content type")

    trace("Done showing page")


if __name__ == '__main__':
    main()