forked from willforde/plugin.video.metalvideo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddon.py
333 lines (285 loc) · 12 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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# -*- coding: utf-8 -*-
# Copyright: (c) 2016 William Forde ([email protected])
#
# License: GPLv2, see LICENSE for more details
#
# 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
# of the License, 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from __future__ import unicode_literals
from codequick import Route, Resolver, Listitem, utils, run
import xbmcgui
import re
# Localized string Constants
VIDEO_OF_THE_DAY = 30004
WATCHING_NOW = 30005
TOP_VIDEOS = 30002
SELECT_TOP = 30001
PARTY_MODE = 589
# Base url constructor
url_constructor = utils.urljoin_partial("http://metalvideo.com")
# Patterens to extract video url
# Copied from the Youtube-DL project
# https://github.com/rg3/youtube-dl/blob/4471affc348af40409188f133786780edd969623/youtube_dl/extractor/youtube.py#L329
VALID_URL = r"""(?x)^
(
(?:https?://|//) # http(s):// or protocol-independent URL
(?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
(?:.*?\#/)? # handle anchor (#/) redirect urls
(?: # the various things that can precede the ID:
(?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
|(?: # or the v= param in all its forms
(?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
(?:\?|\#!?) # the params delimiter ? or # or #!
(?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or
v= # ?s=tuff&v=V36LpHqtcDY)
)
))
|(?:
youtu\.be| # just youtu.be/xxxx
vid\.plus| # or vid.plus/xxxx
zwearz\.com/watch| # or zwearz.com/watch/xxxx
))
)? # all until now is optional -> you can pass the naked ID
([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
(?(1).+)? # if we found the ID, everything can follow
$"""
# noinspection PyUnusedLocal
@Route.register
def root(plugin, content_type="video"):
"""
:param Route plugin: The plugin parent object.
:param str content_type: The type of content been listed e.g. video, music. This is passed in from kodi and
we have no use for it as of yet.
"""
yield Listitem.recent(recent_videos)
yield Listitem.from_dict(plugin.localize(TOP_VIDEOS), top_videos)
yield Listitem.from_dict(plugin.localize(WATCHING_NOW), watching_now)
yield Listitem.search(video_list)
# Fetch HTML Source
url = url_constructor("/mobile/category.html")
html = plugin.request.get(url, headers={"Cookie": "COOKIE_DEVICE=mobile"})
root_elem = html.parse(u"ul", attrs={"id": "category_listing"})
for elem in root_elem.iterfind("li"):
a_tag = elem.find("a")
item = Listitem()
# Set label with video count added
item.label = "%s (%s)" % (a_tag.text, elem.find("span").text)
item.set_callback(video_list, cat=a_tag.get("href"))
yield item
# Add the video items here so that show at the end of the listing
yield Listitem.from_dict(plugin.localize(VIDEO_OF_THE_DAY), play_video, params={"url": "index.html"})
yield Listitem.from_dict(plugin.localize(PARTY_MODE), party_play, params={"url": "randomizer.php"})
@Route.register
def recent_videos(plugin, url="newvideos.php"):
"""
:param Route plugin: The plugin parent object.
:param unicode url: The url resource containing recent videos.
"""
# Fetch HTML Source
url = url_constructor(url)
html = plugin.request.get(url)
root_elem = html.parse("div", attrs={"id": "browse_main"})
node = root_elem.find("./div[@id='newvideos_results']")[0]
for elem in node.iterfind("./tr"):
if not elem.attrib:
item = Listitem()
item.art["thumb"] = elem.find(".//img").get("src")
artist = elem[1].text
track = elem[1][0][0].text
item.label = "%s - %s" % (artist, track)
item.info["artist"] = [artist]
url = elem.find(".//a").get("href")
item.context.related(related, url=url)
item.set_callback(play_video, url=url)
yield item
# Fetch next page url
next_tag = root_elem.findall("./div[@class='pagination']/a")
if next_tag and next_tag[-1].text.startswith("next"):
yield Listitem.next_page(url=next_tag[-1].get("href"))
@Route.register
def watching_now(plugin):
# Fetch HTML Source
url = url_constructor("/index.html")
html = plugin.request.get(url)
root_elem = html.parse("ul", attrs={"id": "mycarousel"})
for elem in root_elem.iterfind("li"):
a_tag = elem.find(".//a[@title]")
item = Listitem()
# Fetch label & thumb
item.label = a_tag.text
item.art["thumb"] = elem.find(".//img").get("src")
url = a_tag.get("href")
item.context.related(related, url=url)
item.set_callback(play_video, url=url)
yield item
@Route.register
def top_videos(plugin):
""":param Route plugin: The plugin parent object."""
# Fetch HTML Source
plugin.cache_to_disc = True
url = url_constructor("/topvideos.html")
html = plugin.request.get(url)
titles = []
urls = []
# Parse categories
root_elem = html.parse("select", attrs={"name": "categories"})
for group in root_elem.iterfind("optgroup"):
for elem in group:
urls.append(elem.get("value"))
titles.append(elem.text.strip())
# Display list for Selection
dialog = xbmcgui.Dialog()
ret = dialog.select(plugin.localize(SELECT_TOP), titles)
if ret >= 0:
# Fetch HTML Source
url = urls[ret]
html = plugin.request.get(url)
root_elem = html.parse("div", attrs={"id": "topvideos_results"})
for elem in root_elem.iterfind(".//tr"):
if not elem.attrib:
item = Listitem()
a_tag = elem[3][0]
artist = elem[2].text
item.label = "%s %s - %s" % (elem[0].text, artist, a_tag.text)
item.art["thumb"] = elem.find(".//img").get("src")
item.info["count"] = elem[4].text.replace(",", "")
item.info["artist"] = [artist]
url = a_tag.get("href")
item.context.related(related, url=url)
item.set_callback(play_video, url=url)
yield item
else:
yield False
@Route.register
def related(plugin, url):
"""
:param Route plugin: The plugin parent object.
:param unicode url: The url of a video.
"""
# Fetch HTML Source
url = url_constructor(url)
html = plugin.request.get(url)
root_elem = html.parse("div", attrs={"id": "tabs_related"})
# Parse the xml
for elem in root_elem.iterfind(u"div"):
a_tag = elem.find("./a[@class='song_name']")
item = Listitem()
item.label = a_tag.text
item.art["thumb"] = elem.find("./a/img").get("src")
url = a_tag.get("href")
item.context.related(related, url=url)
item.set_callback(play_video, url=url)
yield item
@Route.register
def video_list(plugin, url=None, cat=None, search_query=None):
"""
:param Route plugin: The plugin parent object.
:param unicode url: The url resource containing lists of videos or next page.
:param unicode cat: A category url e.g. Alternative, Folk Metal.
:param unicode search_query: The video search term to use for searching.
"""
if search_query:
url = url_constructor("search.php?keywords=%s&btn=Search" % search_query)
elif cat:
sortby = (u"date.html", u"artist.html", u"rating.html", u"views.html")[plugin.setting.get_int("sort")]
base, _ = url_constructor(cat).rsplit("-", 1)
url = "-".join((base, sortby))
else:
url = url_constructor(url)
html = plugin.request.get(url)
root_elem = html.parse("div", attrs={"id": "browse_main"})
for elem in root_elem.iterfind(u".//div[@class='video_i']"):
item = Listitem()
item.art["thumb"] = elem.find(".//img").get("src")
# Extract url and remove first 'a' tag section
# This makes it easir to extract 'artist' and 'song' name later
a_tag = elem.find("a")
url = a_tag.get("href")
elem.remove(a_tag)
# Fetch title
span_tags = tuple(node.text for node in elem.findall(".//span"))
item.label = "%s - %s" % span_tags
item.info["artist"] = [span_tags[0]]
# Add related video context item
item.context.related(related, url=url)
item.set_callback(play_video, url=url)
yield item
# Fetch next page url
next_tag = root_elem.findall(".//div[@class='pagination']/a")
if next_tag and next_tag[-1].text.startswith("next"):
yield Listitem.next_page(url=next_tag[-1].get("href"))
def embeded_videos(video_elem):
urls = []
urls.extend(video_elem.findall(".//iframe[@src]"))
urls.extend(video_elem.findall(".//embed[@src]"))
for url in urls:
yield url.get("src")
@Resolver.register
def play_video(plugin, url):
"""
:param Resolver plugin: The plugin parent object.
:param unicode url: The url of a video.
:returns: A playable video url.
"""
url = url_constructor(url)
html = plugin.request.get(url, max_age=0)
try:
video_elem = html.parse("div", attrs={"id": "Playerholder"})
except RuntimeError:
return None
# Attemp to find url using extract_source(YTDL) first
video_urls = embeded_videos(video_elem)
for url in video_urls:
match = re.match(VALID_URL, url)
if match is not None:
videoid = match.group(2)
return "plugin://plugin.video.youtube/play/?video_id={}".format(videoid)
# Attemp to search for flash file
search_regx = 'clips.+?url:\s*\'(http://metalvideo\.com/videos.php\?vid=\S+)\''
match = re.search(search_regx, html.text)
plugin.logger.debug(match)
if match is not None:
return match.group(1)
# Attemp to search for direct file
search_regx = 'file:\s+\'(\S+?)\''
match = re.search(search_regx, html.text)
if match is not None:
return match.group(1)
@Resolver.register
def party_play(plugin, url):
"""
:param Resolver plugin: The plugin parent object.
:param unicode url: The url to a video.
:return: A playlist with the first item been a playable video url and the seconde been a callback url that
will fetch the next video url to play.
"""
# Attempt to fetch a video url 3 times
attempts = 0
while attempts < 3:
try:
video_url = play_video(plugin, url)
except Exception as e:
# Raise the Exception if we are on the last run of the loop
if attempts == 2:
raise e
else:
if video_url:
# Break from loop when we have a url
return plugin.create_loopback(video_url)
# Increment attempts counter
attempts += 1
# Initiate Startup
if __name__ == "__main__":
run()