-
Notifications
You must be signed in to change notification settings - Fork 0
/
macro.py
executable file
·276 lines (206 loc) · 9.69 KB
/
macro.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
""" Movie plugin for Trac.
Embeds various online movies.
"""
from urlparse import urlparse, urlunparse
from genshi.builder import tag
from trac.core import *
from trac.wiki.api import IWikiMacroProvider, parse_args
from trac.web.chrome import ITemplateProvider, add_script
from trac.wiki.macros import WikiMacroBase
EMBED_COUNT = '_moviemacro_embed_count'
FLOWPLAYER_EMBEDDED = '_moviemacro_flowplayer_embedded'
def get_absolute_url(base, url):
""" Generate an absolute url from the url with the special schemes
{htdocs,chrome,ticket,wiki,source} simply return the url if given with
{http,https,ftp} schemes.
Examples:
http://example.com/filename.ext
ie. http://www.google.com/logo.jpg
chrome://site/filename.ext
htdocs://img/filename.ext
note: `chrome` is an alias for `htdocs`
ticket://number/attachment.pdf
ie. ticket://123/specification.pdf
wiki://WikiWord/attachment.jpg
source://changeset/path/filename.ext
ie. source://1024/trunk/docs/README
"""
def ujoin(*parts):
""" Remove double slashes.
"""
parts = [part.strip('/') for part in parts]
url = '/' + '/'.join(parts)
url = url.replace('//', '/')
return url
scheme, netloc, path, query, params, fragment = urlparse(url)
if scheme in ('ftp', 'http', 'https'):
return url
if scheme in ('htdocs', 'chrome'):
return ujoin(base, 'chrome', path)
if scheme in ('source',):
return ujoin(base, 'export', path)
if scheme in ('ticket',):
return ujoin(base, 'raw-attachment/ticket', path)
if scheme in ('wiki',):
return ujoin(base, 'raw-attachment/wiki', netloc, path)
return url
def string_keys(d):
""" Convert unicode keys into string keys, suiable for func(**d) use.
"""
sdict = {}
for key, value in d.items():
sdict[str(key)] = value
return sdict
def xform_style(style):
""" Convert between a style-string and a style-dictionary.
"""
if isinstance(style, dict):
result = '; '.join(['%s: %s' % (k, v) for k, v in style.items()])
if result:
result += ';'
else:
result = style.split(';')
while '' in result:
result.remove('')
result = dict((s.strip() for s in i.split(':', 1)) for i in result)
return result
def xform_query(query):
""" Convert between a query-string and a query-dictionary.
"""
if isinstance(query, dict):
result = '&'.join(['%s=%s' % (k, v) for k, v in query.items()])
else:
result = query.split('&')
while '' in result:
result.remove('')
result = dict((s.strip() for s in i.split('=', 1)) for i in result)
return result
class MovieMacro(WikiMacroBase):
""" Embed online movies from YouTube, GoogleVideo and MetaCafe, and local
movies via FlowPlayer.
"""
implements(ITemplateProvider)
# IWikiMacroProvider methods
def expand_macro(self, formatter, name, content):
args, kwargs = parse_args(content, strict=True)
kwargs = string_keys(kwargs)
if len(args) >= 1:
url = args[0]
elif len(args) == 0:
raise TracError('URL to a movie at least required.')
embed_count = getattr(formatter, EMBED_COUNT, 0)
embed_count += 1
setattr(formatter, EMBED_COUNT, embed_count)
flowplayer_embedded = getattr(formatter, FLOWPLAYER_EMBEDDED, False)
url = get_absolute_url(formatter.href.base, url)
src = get_absolute_url(formatter.href.base, kwargs.pop('splash','htdocs://movie/movie/img/black.jpg'))
scheme, netloc, path, params, query, fragment = urlparse(url)
try:
style_dict = xform_style(kwargs.get('style', ''))
except:
raise TracError('Double check the `style` argument.')
style = {
'display': 'block',
'border': style_dict.get('border', 'none'),
'margin': style_dict.get('margin', '0 auto'),
'clear': 'both'
}
if netloc == 'www.youtube.com' or netloc == 'www.youtube-nocookie.com':
query_dict = xform_query(query)
video = query_dict.get('v')
url = urlunparse((scheme, netloc, '/v/%s' % video, '', '', ''))
width = kwargs.pop('width', style_dict.get('width', '425px'))
height = kwargs.pop('height', style_dict.get('height', '344px'))
style.update({
'width': width,
'height': height,
})
return tag.object(tag.param(name='movie', value=url),
tag.param(name='allowFullScreen', value='true'),
tag.embed(src=url, type='application/x-shockwave-flash', allowfullscreen='true', width=width, height=height),
style=xform_style(style))
if netloc == 'video.google.com':
query_dict = xform_query(query)
query_dict['hl'] = 'en'
query_dict['fs'] = 'true'
query = xform_query(query_dict)
url = urlunparse((scheme, netloc, '/googleplayer.swf', '', query, ''))
width = kwargs.pop('width', style_dict.get('width', '400px'))
height = kwargs.pop('height', style_dict.get('height', '326px'))
style.update({
'width': width,
'height': height,
})
return tag.embed(src=url,
allowFullScreen='true',
allowScriptAccess='always',
type='application/x-shockwave-flash',
style=xform_style(style))
if netloc == 'www.metacafe.com':
parts = path.split('/')
try:
path = '/fplayer/%s/%s.swf' % (parts[2], parts[3])
except:
raise TracError("Non-standard URL, don't know how to process it, file a ticket please.")
url = urlunparse((scheme, netloc, path, '', '', ''))
width = kwargs.pop('width', style_dict.get('width', '400px'))
height = kwargs.pop('height', style_dict.get('height', '345px'))
style.update({
'width': width,
'height': height,
})
return tag.embed(src=url,
wmode='transparent',
pluginspage='http://www.macromedia.com/go/getflashplayer',
type='application/x-shockwave-flash',
style=xform_style(style))
# Requested by Zach, #4188.
if netloc in ('vimeo.com', 'www.vimeo.com'):
parts = path.split('/')
while '' in parts:
parts.remove('')
path = '/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1' % parts[0]
url = urlunparse((scheme, netloc, path, '', '', ''))
width = kwargs.pop('width', style_dict.get('width', '640px'))
height = kwargs.pop('height', style_dict.get('height', '401px'))
style.update({
'width': width,
'height': height,
})
return tag.object(tag.param(name='movie', value=url),
tag.param(name='allowfullscreen', value='true'),
tag.param(name='allowscriptaccess', value='always'),
tag.embed(src=url, type='application/x-shockwave-flash', allowfullscreen='true', allowscriptaccess='always', width=width, height=height),
style=xform_style(style))
# Local movies.
tags = []
if not flowplayer_embedded:
add_script(formatter.req, 'movie/js/flowplayer.min.js')
add_script(formatter.req, 'movie/js/flowplayer.embed.min.js')
add_script(formatter.req, 'movie/js/flashembed.min.js')
script = '''
$(function() {
$f("a.flowplayer","%s");
});
''' % get_absolute_url(formatter.href.base, 'htdocs://movie/movie/swf/flowplayer.swf')
tags.append(tag.script(script))
setattr(formatter, FLOWPLAYER_EMBEDDED, True)
width = kwargs.pop('width', style_dict.get('width', '320px'))
height = kwargs.pop('height', style_dict.get('height', '320px'))
style.update({
'width': width,
'height': height,
})
if kwargs.pop('clear', None) == 'none':
style.pop('clear')
kwargs = {'style': xform_style(style)}
tags.append(tag.a(tag.img(src=src, **kwargs), class_='flowplayer', href=url, **kwargs))
return ''.join([str(i) for i in tags])
# ITemplateProvider methods
def get_htdocs_dirs(self):
""" Makes the 'htdocs' folder inside the egg available.
"""
from pkg_resources import resource_filename
return [('movie', resource_filename('movie', 'htdocs'))]
def get_templates_dirs(self):
return [] # must return an iterable