summaryrefslogtreecommitdiff
path: root/default.py
blob: db61881ffff92ecfa6404671756eda7f18c01503 (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
# -*- 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 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?

SiteCache = simplecache.SimpleCache()   # FIXME: avoid this global

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)
        self.content_type = self.args.get('content_type', None)

    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):
    cache_id = PLUGIN_NAME + '.url.' + url
    cached_read = SiteCache.get(cache_id)
    if cached_read:
        return cached_read

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

    SiteCache.set(cache_id, response.content,
                    expiration=datetime.timedelta(days=1))
    return response.text


def get_show_title(base_url, path):
    url = base_url + '/' + path
    page = read_url(url)
    parsed = BeautifulSoup(page, "html.parser")
    title = parsed.title.string
    title = re.sub('[|-].*', '', title)
    return title


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 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)))
    items = []
    for a in anchors:
        path = a.get('href')
        show_id = re.sub('.*=', '', path)
        title = get_show_title(KAN_URL, path)
        checksum = title_checksum(title)
        url = page.build_url({'mode': 'show', 'id': show_id,
                              'checksum': str(checksum)})
        items.append((title, url))
    page.build_page(items, isFolder=True)
    SiteCache.set(cache_id, 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 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 main():
    page = Page(sys.argv)

    trace(' | '.join(sys.argv))
    trace("{}".format(page))
    if page.mode is not None:
        mode = page.mode[0]

    if page.mode is None:
        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))
    trace("Done showing page")


if __name__ == '__main__':
    main()