/
Types.py
614 lines (474 loc) · 16.9 KB
/
Types.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
""" Glue together Plone schema with mobapp / pangea types.
This maps, for example, an RFA 'story' to a BBG "Article"
"""
import datetime
from pytz import timezone
from pytz import UTC
import urlparse
from os.path import basename
from zope.component import getMultiAdapter
from Acquisition import aq_inner,aq_parent
from Products.CMFCore.utils import getToolByName
from AccessControl import allow_class
from Products.rfasite.interfaces import IAllowed
from Products.rfasite.interfaces import IImage, ISlideshow
from rfa.kaltura.interfaces import IKalturaVideo
import utils
def format_date(date, tzinfo=None):
### TODO: calling this function with the Plone default datetime (year=1000)
### will generate exceptions. This case must be handled
### This can be aggrivated by requesting an article that does not exist,
### through articles.xml view, among other ways.
#Are we a datetime or a DateTime?
if hasattr(date, 'utcdatetime'): #we are a Zope DateTime!
date = date.utcdatetime()
#else: #we are a python datetime!
# date = date
#calling this function 'naive' will attach a UTC timezone
if date.tzinfo is None and tzinfo is None:
date = UTC.localize(date)
#calling this function with a tzinfo arg will:
elif tzinfo is not None:
if date.tzinfo is None: #localize an existing naive datetime
date = tzinfo.localize(date)
else: #convert a non-naive datetime into the provided timezone
date = date.astimezone(tzinfo)
if date.tzinfo.tzname(date) is not None:
return date.strftime("%a, %d %b %Y %H:%M:%S %Z")
else: #we only have a UTC offset
return date.strftime("%a, %d %b %Y %H:%M:%S %z")
class Placeholder_Article(object):
"""A representation of a "Null" Article"""
default_id = "_placeholder_id"
placeholder = True
def __init__(self):
self._pubDate = None
self._title = None
self._content = None
self._id = None
self._url = None
@property
def id(self):
if self._id is None:
return self.default_id
else:
return self._id
@id.setter
def id(self, value):
self._id = value
def zone(self):
return 0
@property
def pubDate(self):
if self._pubDate is None:
return format_date(datetime.datetime(1900,1,1,0,0))
else:
return format_date(self._pubDate)
@pubDate.setter
def pubDate(self, datetime_value):
self._pubDate = datetime_value
@property
def url(self):
#written this way for readability & maintainability, don't change.
if self._url is None:
return None
else:
return self._url
@url.setter
def url(self, value):
self._url = value
def twitter(self):
return None
@property
def title(self):
if self._title is None:
return "placeholder article"
else:
return self._title
@title.setter
def title(self, value):
self._title = value
@property
def content(self):
if self._content is None:
return "placeholder article"
else:
return self._content
@content.setter
def content(self, value):
self._content = value
def audio(self):
return None
def video(self):
return None
def image(self):
return None
def authors(self):
return []
class Placeholder_Author(object):
"""A representation of a "Null" Author"""
#This should really never happen, but it's used when Plone returns "None" for a lookup on an author id.
placeholder = True
def getUser(self):
class fakeuser(object):
def getId(self):
return "None"
return fakeuser()
def getProperty(self, prop):
return ""
class AudioClip(object):
def __init__(self, ploneObj=None, streamerSegment=None, localTz=None):
if not any([ploneObj, streamerSegment]):
raise ValueError, "must provide either ploneObj or streamerSegment to AudioClip init"
self.obj = ploneObj
self.segment = streamerSegment
self.localTz = localTz
def __filename(self):
if self.obj:
try:
return self.obj.getFilename()
except AttributeError:
return self.obj.id
else:
parsed = urlparse.urlparse(self.segment['url'])
return basename(parsed.path)
def id(self):
if self.obj:
return self.obj.UID()
else:
return self.__filename()
def duration(self):
#TODO: Figure out a way to get the 'duration' of an audio clip.
return 5400 #90 mins - just a non-zero number
def url(self):
if self.obj:
url = self.obj.absolute_url()
if not url.endswith(".mp3"):
url +="?f="+self.obj.getFilename()
return url
else:
return self.segment['streaming_url']
def _dateUTC(self):
if self.obj:
if self.obj.effective().year() > 2000:
date = self.obj.effective()
else:
date = self.obj.created()
else:
date = self.segment['filedate']
return date
def date(self):
return format_date(self._dateUTC())
def datelocal(self):
if self.obj:
return None #TODO
else:
localdate = self._dateUTC().astimezone(self.localTz)
return format_date(localdate)
def title(self):
if self.obj:
return self.obj.Title()
else:
return self.segment['lang']
def description(self):
if self.obj:
return self.obj.Description()
else:
return self.title()
def audioType(self):
#type of audio (c-clip, f-feature or b-broadcastProgram)
if self.segment:
return 'b'
else:
return 'c'
def mime(self):
try:
return self.obj.getContentType()
except AttributeError:
mt_tool = getToolByName(self.obj.getSubsite(), "mimetypes_registry")
return mt_tool.lookupExtension(self.__filename())
class Media(object):
_parent = None
def __init__(self):
raise NotImplementedError, "Can't instantiate abstract parent 'media'"
@property
def article_parent(self):
"""Returns a Placeholder_Article if Media has no parent that's a Story
Otherwise, return the story this Media object is contained within
"""
if self._parent is not None:
return self._parent
#There MUST be a better way to do this...
obj = self.obj
while obj is not None \
and getattr(obj, 'portal_type', None) is not None \
and obj.portal_type != "Story":
obj = aq_parent(aq_inner(obj))
if getattr(obj, 'portal_type', None) is None:
self._parent = Placeholder_Article()
else:
self._parent = _Article(obj)
return self._parent
@property
def article_parent_id(self):
return self.article_parent.id
class Image(Media):
def __init__(self, imgObj, order=0):
self.obj = imgObj
self.order = None
def id(self):
return self.obj.UID()
def type(self):
return self.obj.get_content_type()
def url(self):
return self.obj.absolute_url()
def title(self):
title = self.obj.getCaption()
if not title:
title = self.obj.Description() #aka 'alt text'
if not title:
return None
else:
return title
def width(self):
return self.obj.width
def height(self):
return self.obj.height
def description(self):
return self.obj.CaptionOrTitle()
class PhotoGallery(Media):
def __init__(self, obj=[], g_id="NaN", title=""):
self._images = list()
self.id = g_id
self.title=title
self.obj = obj
if ISlideshow.providedBy(obj):
if g_id=="NaN":
self.id = obj.UID()
if title=="":
self.title = obj.Title()
self.addSlideshow(obj)
elif IImage.providedBy(obj):
self.addImage(obj)
else:
for image in obj:
if IImage.providedBy(image):
self.addImage(image)
def __getitem__(self, index):
return self._images[index]
def __len__(self):
return self.count
def __iter__(self):
#thread safe? you wish!
i=0
while i < self.count:
yield self._images[i]
i+=1
raise StopIteration
def photos(self):
return self._images
def addImage(self, image):
image.order=self.count
self._images.append(image)
@property
def count(self):
return len(self._images)
def addSlideshow(self, slideshow):
### check slideshow values to make sure they are plone image type.
for ATimage in slideshow.values():
image = Image(ATimage)
self.addImage(image)
def mergeGallery(self, gallery):
"""provided another PhotoGallery type, merge it into this one"""
if gallery is self:
raise AssertionError, "merging with yourself is not really a good idea. If you really meant to do this, use copy()"
for image in gallery:
self.addImage(image)
def setId(self, g_id):
self.id = g_id
class Video(Media):
"""Mobapp representation of a video"""
def __init__(self, obj):
self.obj = obj
self.kalturaObj = getattr(self.obj, 'KalturaObject', None)
#if we are a video within a bogus 'placeholder' article,
#set attributes on the placeholder to make the mobile app work correctly.
if self.article_parent.placeholder:
self.article_parent.title = self.title()
self.article_parent.content = None
self.article_parent.id = self.guid()
self.article_parent.url = self.vidpageUrl()
#try using the date from plone video object.
if self.obj.effective().year() > 1000: #if it's not set, year will be 1000
self.article_parent.pubDate = self.obj.effective()
else:
#use the date in the kalturaObject
self.article_parent.pubDate = datetime.datetime.fromtimestamp(self.kalturaObj.getUpdatedAt())
def id(self):
return self.guid()
def relType(self):
"""Defines relation between article and video => 0=SameItem, 1=MainImage,2=EmbededInContent"""
#if this video is wrapped in a placeholder, then it's a stand-alone video and should be considered 'sameItem'
if self.article_parent.placeholder:
return 0
return 2 #otherwise, it's a video embedded in a story
def duration(self):
"""Duration of the video data (seconds)"""
return 600 #XXX TODO
def width(self):
"""Width (pixels) of the video"""
return 176 #XXX TODO
def height(self):
"""Height (pixels) of the video"""
return 144 #XXX TODO
def url(self):
"""Location of the video file"""
if self.kalturaObj:
return self.kalturaObj.dataUrl
else:
return None
def vidpageUrl(self):
#XXX does not support dynamic video page name
#XXX makes assumption that video page is always
# rfa.org/language/video
base = self.obj.getSubsite().absolute_url()
url = base + '/video' + '?v={entryId}'
return url.format(entryId=self.kalturaObj.getId())
def date(self):
"""Publication date"""
return datetime.datetime.now() ###TODO
#return self.article_parent.pubDate(date)
def title(self):
"""Title of the video item"""
return self.obj.Title()
def description(self):
"""Description for the video item"""
return self.obj.Description()
def guid(self):
return self.obj.UID()
def thumbnail(self):
url = self.kalturaObj.getThumbnailUrl()
return url
class _Article(Placeholder_Article):
placeholder = False
def __init__(self, obj, request=None):
self.obj = obj
self.request = request
self._gallery = None
self._video = None
@property
def id(self):
return self.obj.UID()
def zone(self):
return aq_parent(self.obj).UID()
@property
def pubDate(self):
return format_date(self.obj.effective())
def url(self):
return self.obj.absolute_url()
def twitter(self):
##TODO: add url shortening.
return self.url()
def title(self):
return self.obj.Title()
def content(self):
renderedText = self.obj.getText()
return utils.cleanHtml(renderedText)
def intro(self):
return self.obj.Description()
def audios(self):
###XXX IAllowed not working here
#ac_allowed = IAllowed(self.obj.getAudioClip())
#audio_obj = ac_allowed.allowedOrNone()
clips = self.obj.getAudioClip()
if clips:
return [AudioClip(clip) for clip in clips]
else:
return []
def audio(self):
"""For those who want only one audio clip"""
clips = self.audios()
if clips:
return clips[0]
else:
return None
def video(self):
"""return a single kalturaVideo as a Video within the cp_container body slot"""
#Videos are embedded via the Layout Tab, so we must journey into cp_container to find it.
cp = getattr(self.obj, 'cp_container', None)
if cp is None:
return None
if self._video is not None:
return self._video
slot = cp.filled_slots['body']
for elem in slot.values():
obj = elem.getTarget()
if IKalturaVideo.providedBy(obj): #XXX use IVideo when it appears - IKalturaVideo should inherit from it.
#be lazy. The first Video you find is all you get!
self._video = Video(obj)
return self._video
return self._video
@property
def gallery(self):
"""return a single rfasite.slideshow as a PhotoGallery associated with the article"""
#slideshows are embedded via the Layout Tab, so we must journey into cp_container to find it.
cp = getattr(self.obj, 'cp_container', None)
if cp is None:
return None
if self._gallery is not None:
return self._gallery
slots = cp.filled_slots.values()
for slot in slots:
for elem in slot.values():
obj = elem.getTarget()
if ISlideshow.providedBy(obj):
#be lazy. The first gallery you find is all you get!
self._gallery = PhotoGallery(obj)
return self._gallery
@gallery.setter
def gallery(self, obj):
if isinstance(obj, PhotoGallery):
self._gallery = obj
else:
raise TypeError, "Not a PhotoGallery Object"
def image(self):
imgObj = self.obj.getFeaturedImage()
if imgObj is None:
return None
return Image(self.obj.getFeaturedImage())
def authors(self):
"""an author is a dictionary containing keys 'first', 'middle', 'last', 'email', 'id'
this returns an iterable of authors
"""
authors = []
if hasattr(self.obj, "getByline") and self.obj.getByline():
authors.append({"id": None,
"first": None,
"middle": None,
"last": self.obj.getByline(),
"email": None,
"description": None,
})
if len(authors):
return authors
else:
return None
allow_class(_Article)
class ArticleFactory(object):
def __init__(self, lookupObj_func, request=None):
self.getObject = lookupObj_func
self.request = request
def makeArticle(self, uid=None, obj=None, request=None):
#if uid and object are both none, throw an exception.
if uid is not None:
obj = self.getObject(uid)
obj = aq_inner(obj)
if obj is None:
return None
elif obj is None:
raise TypeError, "makeArticle takes a non-None uid or object argument"
if request is None:
request = self.request
return _Article(obj, request=request)
def __call__(self, uid=None, obj=None, request=None):
return self.makeArticle(uid, obj, request)