-
Notifications
You must be signed in to change notification settings - Fork 6
/
addon.py
executable file
·245 lines (188 loc) · 9.31 KB
/
addon.py
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
import xbmcaddon
import xbmcgui
import xbmcplugin
import sys
from urlparse import parse_qsl
from urllib import urlencode
import requests
import util
from resources.lib.lynda_api import LyndaApi
from google_analytics import GoogleAnalytics
addon = xbmcaddon.Addon()
addonname = addon.getAddonInfo('name')
# Get the plugin url in plugin:// notation.
__url__ = sys.argv[0]
# Get the plugin handle as an integer number.
__handle__ = int(sys.argv[1])
__version__ = addon.getAddonInfo("version")
class LyndaAddon:
COOKIE_FILE_NAME = 'lynda_cookies'
TOKEN_USER_INPUT = 'user_login_token'
def __init__(self):
self.ga = GoogleAnalytics(addon, __version__)
def show_listing(self, listing):
"""Show a listing on the screen."""
xbmcplugin.addDirectoryItems(__handle__, listing, len(listing))
xbmcplugin.endOfDirectory(__handle__)
def list_root_options(self):
"""Create the list of root options in the Kodi interface."""
listing = []
# Add search courses list item
list_item = xbmcgui.ListItem(label="Search Courses")
url = '{0}?action=search&type={1}'.format(__url__, "course")
is_folder = True
listing.append((url, list_item, is_folder))
# Add browse course categories list item
# list_item = xbmcgui.ListItem(label="Browse Course Categories")
# url = '{0}?action=list_categories_letters'.format(__url__)
# is_folder = True
# listing.append((url, list_item, is_folder))
if self.api.logged_in:
# Add my courses list item
list_item = xbmcgui.ListItem(label="My Courses")
url = '{0}?action=list_my_courses'.format(__url__)
is_folder = True
listing.append((url, list_item, is_folder))
if self.api.logged_in:
logged_in_text = "Logged in as " + self.api.user().name
else:
logged_in_text = "Not logged in"
# Add the logged in status list item
list_item = xbmcgui.ListItem(label=logged_in_text)
url = ''
is_folder = False
listing.append((url, list_item, is_folder))
if self.api.logged_in:
list_item = xbmcgui.ListItem(label="Refresh login credentials")
url = '{0}?action=refresh_login'.format(__url__)
is_folder = False
listing.append((url, list_item, is_folder))
self.show_listing(listing)
def list_courses(self, courses):
"""Show a list of courses given a list of course objects."""
listing = []
for course in courses:
list_item = xbmcgui.ListItem(label=course.title, thumbnailImage=course.thumb_url)
url = '{0}?action=list_course_chapters&course_id={1}'.format(__url__, course.course_id)
is_folder = True
list_item.setInfo("video", {"plot": course.description})
listing.append((url, list_item, is_folder))
self.show_listing(listing)
def list_course_chapters(self, course_id):
"""Show the list of course chapters in the Kodi interface."""
chapters = self.api.course_chapters(course_id)
listing = []
for chapter in chapters:
list_item = xbmcgui.ListItem(label=chapter.title)
url = '{0}?action=list_chapter_videos&course_id={1}&chapter_id={2}'.format(__url__, course_id, chapter.chapter_id)
is_folder = True
listing.append((url, list_item, is_folder))
self.show_listing(listing)
def list_chapter_videos(self, course_id, chapter_id):
"""Show a list of playable videos within a chapter in the Kodi interface."""
videos = self.api.chapter_videos(course_id, chapter_id)
listing = []
for video in videos:
list_item = xbmcgui.ListItem(label=video.title)
is_folder = False
if video.has_access:
list_item.setProperty('IsPlayable', 'true')
url = '{0}?action=play&course_id={1}&video_id={2}'.format(__url__, course_id, video.video_id)
else:
url = '{0}?action=show_access_error'.format(__url__)
listing.append((url, list_item, is_folder))
self.show_listing(listing)
def show_access_error(self):
xbmcgui.Dialog().ok(addonname, "Access error.", "You do not have access to this video. Please login to view this video.")
def play_video(self, course_id, video_id):
"""Play a video by the provided (lynda.com) video ID."""
path = self.api.video_url(course_id, video_id)
play_item = xbmcgui.ListItem(path=path)
# Play the video
xbmcplugin.setResolvedUrl(__handle__, True, listitem=play_item)
def search(self):
keyboard = xbmc.Keyboard("", "Search", False)
keyboard.doModal()
if keyboard.isConfirmed() and keyboard.getText() != "":
query = keyboard.getText()
courses = self.api.course_search(query)
self.list_courses(courses)
def list_my_courses(self):
courses = self.api.user_courses()
self.list_courses(courses)
def login(self, auth_type):
if auth_type == "Normal Lynda.com Account":
username = xbmcplugin.getSetting(__handle__, "username")
password = xbmcplugin.getSetting(__handle__, "password")
login_success = self.api.login_normal(username, password)
if not login_success:
xbmcgui.Dialog().ok(addonname, "Could not login.", "Please check your credentials are correct.")
elif auth_type == 'Organisation':
login_token = util.load_text(addon, self.TOKEN_USER_INPUT) # Can be None if file doesn't exist
if login_token:
login_token = login_token.strip()
print("got login token", login_token)
self.api.set_token(login_token)
user = self.api.user()
if not user:
xbmcgui.Dialog().ok(addonname, "Could not login.", "Please make sure you have a valid login token in the user_login_token file in the addon data directory")
else:
xbmcgui.Dialog().ok(addonname, "Could not login.", "Please make sure you have the user_login_token file with your login token in the addon data directory")
elif auth_type == 'IP Site License':
login_success = self.api.login_ip()
if not login_success:
xbmcgui.Dialog().ok(addonname, "Could not login.", "Your IP may not have a site license.")
def refresh_login(self):
"""Deletes persisted cookies which forces a login attempt with current credentials"""
s = requests.Session()
empty_cookie_jar = s.cookies
if util.save_data(addon, self.COOKIE_FILE_NAME, empty_cookie_jar):
xbmcgui.Dialog().ok(addonname, "Cleared cookies. Please exit the addon and open it again.")
else:
xbmcgui.Dialog().ok(addonname, "Could not refresh lynda session cookies")
def router(self, paramstring):
"""Router function that calls other functions depending on the provided paramstrings"""
# Parse a URL-encoded paramstring to the dictionary of {<parameter>: <value>} elements
params = dict(parse_qsl(paramstring[1:]))
if params:
if params['action'] != 'play':
self.ga.track(params['action'])
# Cookiejar should definitely exist by now. Even if empty
cookiejar = util.load_data(addon, self.COOKIE_FILE_NAME)
self.api = LyndaApi(cookiejar)
if params['action'] == 'search':
self.search()
elif params['action'] == 'list_course_chapters':
self.list_course_chapters(int(params['course_id']))
elif params['action'] == 'list_chapter_videos':
self.list_chapter_videos(int(params['course_id']), int(params['chapter_id']))
elif params['action'] == 'play':
# Log the video as being played if user is logged in
if self.api.logged_in:
self.api.log_video(int(params['video_id']))
self.play_video(int(params['course_id']), int(params['video_id']))
elif params['action'] == 'show_access_error':
self.show_access_error()
elif params['action'] == 'list_my_courses':
self.list_my_courses()
elif params['action'] == 'refresh_login':
self.refresh_login()
else:
self.ga.track('list_root_options')
cookiejar = util.load_data(addon, self.COOKIE_FILE_NAME)
if cookiejar:
self.api = LyndaApi(cookiejar)
else:
self.api = LyndaApi()
auth_type = xbmcplugin.getSetting(__handle__, "auth_type")
# Try to log the user in if necessary
if not self.api.logged_in and auth_type != 'None':
self.login(auth_type)
# Save cookie jar to disk so other screens in addon can resume session
if not util.save_data(addon, self.COOKIE_FILE_NAME, self.api.get_cookies()):
xbmcgui.Dialog().ok(addonname, "Could not save lynda session cookies")
self.list_root_options()
if __name__ == '__main__':
lynda_addon = LyndaAddon()
# Call the router function and pass the plugin call parameters to it
lynda_addon.router(sys.argv[2])