/
browser.py
647 lines (485 loc) · 23.3 KB
/
browser.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
"""ODD Unbrella App RSS Views"""
import datetime
import pytz
from Acquisition import aq_inner
from zope.component import getUtility
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from Products.rfasite.browser import SearchRetailView, RetailNavigationView, AudioArchiveView
from Products.rfasite.livestreams import getLanguageChannels
from Products.rfasite.interfaces import ILiveStreamUrlUtility
import Types
import utils
SITEID = 0 #There is only one site, and it's rfa.org
class MobappBaseView(BrowserView):
MaxArticles = 30
DefaultDays = 30
#TODO: move query to base and populate with, at least, "published" state.
def __init__(self, context, request):
super(MobappBaseView, self).__init__(context, request)
self.cirequest = utils.CaseInsensitiveDict()
for key, value in request.form.iteritems():
self.cirequest[key]=value
#although this should ALWAYS be called in subsite context...
self.subsite = context.getSubsite()
self.SiteID = self.cirequest.get('SiteID', 0) #Ignored.
self.ZoneID = self.cirequest.get("ZoneID", "")
self.ZoneIDs = self.ZoneID.split("|")
if self.ZoneIDs == [""]:
self.ZoneIDs = []
self.Zone = self.cirequest.get("Zone","")
self.Zones = self.Zone.split("|")
if self.Zones == [""]:
self.Zones = []
self.DayCount = int(self.cirequest.get("DayCount", self.DefaultDays))
self.Count = int(self.cirequest.get("Count", 30))
if self.Count > self.MaxArticles:
self.Count=self.MaxArticles
self.ArticleID = self.cirequest.get("ArticleId", None)
self.AuthorID = self.cirequest.get("AuthorId", None)
self.Title = utils.toBool(self.cirequest.get("Title", True))
self.TitleAsCDATA = utils.toBool(self.cirequest.get("TitleAsCDATA", False))
self.Intro = utils.toBool(self.cirequest.get("Introduction", True))
self.IntroAsCDATA = utils.toBool(self.cirequest.get('IntroductionAsCDATA', False))
self.Content = utils.toBool(self.cirequest.get("Content", True))
self.ContentAsCDATA = utils.toBool(self.cirequest.get("ContentAsCDATA", False))
self.Image = utils.toBool(self.cirequest.get("Image", True))
self.ImageTitle = utils.toBool(self.cirequest.get("ImageTitle", True))
self.Authors = utils.toBool(self.cirequest.get("Authors", True))
self.AuthorsFullName = utils.toBool(self.cirequest.get("AuthorsFullName", False))
self.html = utils.toBool(self.cirequest.get("html", False))
if self.html:
self.ContentAsCDATA = True
self.TitleAsCDATA = True
self.catalog = getToolByName(self.context, 'portal_catalog')
if self.Zones:
#we got some Section names we have to look up ID's for
for sectionName in self.Zones:
### IS there a way to get an exact match??????
brains = self.catalog.searchResults(portal_type="Section",Title=sectionName)
uid = brains[0].UID #first element by default
for brain in brains:
if brain.Title.upper()==sectionName.upper():
uid=brain.UID
break
self.ZoneIDs.append(uid)
self.Article = Types.ArticleFactory(lookupObj_func=self.subsite.reference_catalog.lookupObject,
request=self.request)
#set the timezone
tzOffset = getattr(self.context, 'getTimezoneOffset', lambda: 0)()
#we assume US/Eastern when we don't have a timezone offset set.
#XXX we shouldn't set numeric offsets, we should set tzinfo objects to support DST
if tzOffset == 0 or tzOffset is None:
self.subsiteTz = pytz.timezone('US/Eastern')
else:
#convert to minutes
offset = int(tzOffset*60)
self.subsiteTz = pytz.FixedOffset(offset)
def items(self):
self.info = {"site": SITEID,
"showImg": self.Image,
"showTitle": self.Title,
"showImgTitle": self.ImageTitle,
"CDATA_Title": self.TitleAsCDATA,
"showIntro": self.Intro,
"CDATA_Intro": self.IntroAsCDATA,
"showContent": self.Content,
"CDATA_Content": self.ContentAsCDATA,
"showAuthors": self.Authors,
"AuthorFullName": self.AuthorsFullName}
class MobappZoneView(MobappBaseView):
"""zones.zml view"""
def __init__(self, context, request):
super(MobappZoneView, self).__init__(context, request)
if not self.ZoneID:
self.ZoneID = self.subsite.UID()
else:
self.ZoneID = self.ZoneIDs[0]
def getZonesFromNav(self):
"""Return dictionary of zones based on
how the RetailNav returns
"""
view = RetailNavigationView(self.context, self.request)
navs = view.navigation()
zones = self._makeZoneInfo([n['brain'] for n in navs])
return zones
def getZonesFromList(self, zoneList):
"""generates a dictionary of zones based on a configured list of paths relative to subsite
zone = {ZoneId, SiteID, Title, hash, path}
"""
rootPath = '/'.join(self.subsite.getPhysicalPath())
zonePaths = [ rootPath+'/'+id for id in zoneList ]
pathquery = {'query': zonePaths, 'depth': 0}
sectionBrains = self.catalog.searchResults(path=pathquery,
portal_type='Section')
zones = self._makeZoneInfo(sectionBrains)
#preserve order of zones configured for top-level.
for zone_info in zones:
topZoneValue = zone_info['path'][len(rootPath+'/'):]
sortKey = zoneList.index(topZoneValue)
zone_info['sortKey'] = sortKey
zones.sort(key=lambda zone:zone['sortKey'])
return zones
def getZonesFromSubsiteProperty(self):
zoneList = self.subsite.getProperty('mobapp_zones', None)
if zoneList:
return self.getZonesFromList(zoneList)
else:
return None
def getZonesFromPath(self, parentZones):
"""Given a parent zone (section) return all child Sections
Used for 'subzone' query, when zoneID parameter is provided
"""
sectionBrains = self.catalog.searchResults(path=parentZones,
portal_type='Section',
depth=1)
zones = self._makeZoneInfo(sectionBrains)
return zones
def _makeZoneInfo(self, sectionBrains):
""" Turn a set of brains from a catalog query into zone info for templates"""
zones = []
for sectionBrain in sectionBrains:
if publicFolder(sectionBrain):
zone_info = {"ZoneID": sectionBrain.UID,
"SiteID": SITEID,
"Title": sectionBrain.Title,
"hash": utils.getFolderModificationDate(sectionBrain, self.catalog),
"path": sectionBrain.getPath()
}
zones.append(zone_info)
return zones
def items(self):
super(MobappZoneView, self).items()
if self.subsite.UID() == self.ZoneID:
parentZone = self.subsite
else:
parentZone = self.subsite.reference_catalog.lookupObject(self.ZoneID)
if parentZone == self.subsite:
#this is a query from the root:
zones = self.getZonesFromSubsiteProperty()
if zones is None:
#no configuration, use the subsite's default navigation setup.
zones = self.getZonesFromNav()
else:
#this is a query for sub-zones given a zone.
zones = self.getZonesFromPath(parentZone)
self.info["zones"] = zones
return self.info
class MobappArticlesView(MobappBaseView):
def items(self):
super(MobappArticlesView, self).items()
self.info['articles'] = []
if self.ArticleID:
article = self.Article(self.ArticleID)
if article:
self.info["articles"].append(article)
return self.info
query = {}
query['portal_type'] = "Story"
query['review_state'] = "published"
end = datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
start = datetime.datetime.utcnow() - datetime.timedelta(days=self.DayCount)
date_range_query = {'query':(start,end), 'range':'min:max'}
query['effective'] = date_range_query
if self.ZoneIDs:
sectionBrains = self.catalog.searchResults(UID=self.ZoneIDs)
zonePaths = [brain.getPath() for brain in sectionBrains]
query['path'] = {'query':zonePaths, 'depth':3} #depth 3 because of http://webber.rfa.org/trac/ticket/198
if self.AuthorID:
query['Creator'] = self.AuthorID
articleBrains = self.catalog.search(query_request=query,
sort_index = 'effective',
reverse = 1,
limit=self.Count)[:self.Count]
for brain in articleBrains:
article = self.Article(brain.UID, request=self.request)
self.info["articles"].append(article)
return self.info
class MobappAudioArchiveView(MobappBaseView):
def __init__(self, context, request):
super(MobappAudioArchiveView, self).__init__(context, request)
self.AudioId = self.cirequest.get("AudioId", "")
def items(self):
super(MobappAudioArchiveView, self).items()
from Products.rfasite.interfaces import IProgramSegmentsFinder
adapter = IProgramSegmentsFinder(self.subsite)
segments = adapter()
self.info["programs"] = []
#if self.AudioId: #XXX figure out how to look up by ID, if needed
for s in segments:
audioObj = Types.AudioClip(streamerSegment=s, localTz=self.subsiteTz)
if audioObj is not None:
self.info["programs"].append(audioObj)
return self.info
class MobappBreakingNewsView(MobappBaseView):
"""Fakes a breaking news article using the placeholder
All we have is a title at this point"""
def items(self):
super(MobappBreakingNewsView, self).items()
self.info["articles"] = []
breaking_news_string = self.subsite.getBreakingNews()
if breaking_news_string:
article = Types.Placeholder_Article()
article.title = breaking_news_string
article.content = breaking_news_string
article.pubDate = str(datetime.datetime.utcnow()) #TODO - maybe effective on subsite?
self.info["articles"].append(article)
return self.info
class MobappMediaView(MobappBaseView):
"""Present videos and slideshows as a selection of media
"""
DefaultDays = 90
photo_types = ["Slideshow",]
#we need an IVideo interface marker!
#video_types = ["VideoLink", "YoutubeLink", "Kaltura Video"]
video_types = ["Kaltura Video"]
def __init__(self, context, request):
super(MobappMediaView, self).__init__(context, request)
self.Media = self.cirequest.get("media", "").upper()
self.MediaID = self.cirequest.get("MediaId", "")
self.Videos = False
self.Photos = False
if "V" in self.Media:
self.Videos = True
if "P" in self.Media:
self.Photos = True
def add_media(self, media_obj):
dest_article = None
#search to see if we have this article already.
for article in self.info["articles"]:
if article.id == media_obj.article_parent_id and not media_obj.article_parent.placeholder:
dest_article = article #matching article, and it's not a placeholder article
break
if dest_article is None:
dest_article = media_obj.article_parent
self.info["articles"].append(dest_article)
if isinstance(media_obj, Types.PhotoGallery):
dest_article.gallery = media_obj
if isinstance(media_obj, Types.Video):
dest_article.video = media_obj
def query_photos(self):
query ={}
media_types = self.photo_types
if self.ZoneIDs:
sectionBrains = self.catalog.searchResults(UID=self.ZoneIDs)
zonePaths = [brain.getPath() for brain in sectionBrains]
query['path'] = {'query':zonePaths, 'depth':2}
#we search for published articles, and return media within those articles.
# This avoids requiring Slideshows and Videos to be 'published'
query['portal_type'] = "Story"
query['review_state'] = "published"
end = datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
start = datetime.datetime.utcnow() - datetime.timedelta(days=self.DayCount)
query['effective'] = {'query':(start,end), 'range':'min:max'}
articleBrains = self.catalog.search(query_request=query,
sort_index = 'effective',
reverse = 1)
articlePaths = [brain.getPath() for brain in articleBrains]
brains = self.catalog.search(query_request={'portal_type': media_types,
'path': {'query':articlePaths,
'depth':1}
},
limit=self.Count)[:self.Count]
zope_objects = [brain.getObject() for brain in brains]
return zope_objects
def query_videos(self):
query ={}
media_types = self.video_types
#for now, videos (Kaltura) do not have zones - revisit
#if self.ZoneIDs:
# sectionBrains = self.catalog.searchResults(UID=self.ZoneIDs)
# zonePaths = [brain.getPath() for brain in sectionBrains]
# query['path'] = {'query':zonePaths, 'depth':2}
query['portal_type'] = media_types
query['review_state'] = ["published"]
brains = self.catalog.search(query_request=query,
sort_index = 'effective',
reverse = 1,
limit=self.Count)[:self.Count]
zope_objects = [brain.getObject() for brain in brains]
return zope_objects
def items(self):
super(MobappMediaView, self).items()
self.info["articles"] = []
zope_objects = []
if self.MediaID: #provided an id: return just that object
obj = self.subsite.reference_catalog.lookupObject(self.MediaID)
if obj:
zope_objects.append(obj)
else: #we query the catalog
if self.Photos:
zope_objects += self.query_photos()
if self.Videos:
zope_objects += self.query_videos()
for obj in zope_objects:
if obj.portal_type in self.photo_types:
self.add_media(Types.PhotoGallery(obj))
elif obj.portal_type in self.video_types: #IVideo.providedBy(obj) is what this should say.
self.add_media(Types.Video(obj))
return self.info
class MobappSchedulerView(MobappBaseView):
def items(self):
#English service does not have a schedule of programs from RFA
super(MobappSchedulerView, self).items()
self.info["programs"]=[]
return self.info
class MobappSearchView(MobappBaseView, SearchRetailView):
def __init__(self, context, request):
MobappBaseView.__init__(self, context, request)
self.search_text = self.cirequest.get("q", "")
self.results = self._getResults()
#just pass some stuff to batch 1 page
self.b_start = 0
self.b_size = 30
def items(self):
super(MobappSearchView, self).items()
self.info["articles"] = []
if not self.search_text:
#no results if no query
return self.info
articleBrains = self.batch()
for brain in articleBrains:
self.info["articles"].append(self.Article(brain.UID))
return self.info
class MobappTopStoriesView(MobappBaseView):
def __init__(self, context, request):
""" request parameter 'odd' will guarantee an odd number of results returned, if total number of results is greater than 3"""
super(MobappTopStoriesView, self).__init__(context, request)
self.odd = self.cirequest.get("odd", 0) #not implemented
self.Count = 5
def items(self):
super(MobappTopStoriesView, self).items()
self.info["articles"] = []
# First top story is 'the top story'
top_story_obj = self.subsite.getTopStory()
top_story = self.Article(obj=top_story_obj, request=self.request)
self.info["articles"].append(top_story)
query = {'portal_type': "Story",
'review_state': "published",
}
articleBrains = self.catalog.search(query_request=query,
sort_index = 'effective',
reverse = 1,
limit=self.Count)[:self.Count]
#take the top story out of the result, if there
filteredBrains = [brain for brain in articleBrains if brain.UID != top_story_obj.UID()]
#if we didn't take out a story, then truncate the list from the end.
articleBrains = filteredBrains[:4]
for brain in articleBrains:
article = self.Article(brain.UID, request=self.request)
self.info["articles"].append(article)
#assert(len(self.info["articles"]) == self.Count)
return self.info
class MobappConfigView(MobappBaseView):
""" Controlls the configuration of the app: config.xml """
def audioStreamInfo(self):
language = self.context.getLanguage()
channelInfo = getLanguageChannels(language)
streams = []
for channel in channelInfo:
streams.append({"url":channel['url'],
#"title":channel['title'],
"title": "", #TRAC ticket 604
"desc":channel["description"],
"tubeId":channel["id"],
})
return streams
def videoStreamInfo(self):
return None
#return {"url":"Stream URL",
# "title":"stream Title",
# "desc":"stream Description",
# "tubeId":"tubeId"
# }
def feedbackEmail(self):
return self.subsite.getProperty("app_feedbackEmail", "rfaapps@gmail.com")
def bugreportEmail(self):
return self.subsite.getProperty("app_bugreportEmail", "rfaapps@gmail.com")
def socialMedias(self):
info = [ {"name": "Facebook", "url": self.subsite.getProperty("app_facebook", None)},
{"name": "Youtube", "url": self.subsite.getProperty("app_youtube", None)},
{"name": "Twitter", "url": self.subsite.getProperty("app_twitter", None)},
{"name": "SoundCloud", "url": self.subsite.getProperty("app_soundcloud", None)}
]
return info
def twitterHandle(self):
return self.subsite.getProperty("app_twitter_handle", None)
def newsCastZoneId(self):
#return "250"
return None
def bestPracticesUrl(self):
return "http://www.rfa.org/about/help/web_access.html"
class MobappLiveAudioView(MobappBaseView):
""" Live Audio Streams"""
def __init__(self, context, request):
super(MobappLiveAudioView, self).__init__(context, request)
self.streamtool = ILiveStreamUrlUtility(self.subsite)
self.tubeId = self.cirequest.get('tubeId', None)
def title(self):
return "Scheduler"
def program(self):
streaminfo = self.streamtool.streamingInfo()
if len(streaminfo) == 0:
return None
#select the program that corresponds to tubeId:
for program in streaminfo:
if program["channel"]["id"] == self.tubeId:
break #this is the program we want to display
else:
return None #there is no stream to display
program = streaminfo[0]
channel = program['channel']
#so you can datemath
start = datetime.datetime.combine(datetime.datetime.today(), program['start'])
end = datetime.datetime.combine(datetime.datetime.today(), program['end'])
#program/@duration Program duration (second)
duration = (end - start).seconds
#program/@url URL of the audio file(mp3 file).
#This attribute is optional - if it is not specified it
#means that prorgam is currently LIVE
url = None #we are always live... sort of.
#Time when the broadcast program was recorded.
#XXX this should honor the 'rebroadcast' bool,
#but we have no info on what is actually being broacasted
# Therefore, all is 'now, live'
date = datetime.datetime.now(pytz.utc)
#program/@dateLocal Localized datetime of broadcasting,
#with GMT offset included
#XXX Revisit when subsites have a timezone
# instead of UTC offset
offset = pytz.FixedOffset(self.subsite.getTimezoneOffset()*60)
dateLocal = datetime.datetime.now(offset)
#program/@timeLeft Remaining time of program (second)
#This attribute is optional - if it is not specified it means
#that program is RECORDED or UNKNOWN LIVE PROGRAM ON AIR
timeLeft = (end - datetime.datetime.now(pytz.utc)).seconds
#programTitle = channel['title']
programTitle = "" #TRAC 604
programDescription = channel['description'] #XXX get channel description
url = channel['url']
info = {'id':'NoID',
'duration':duration,
'date':date,
'datelocal':dateLocal,
'timeleft':timeLeft,
'title':programTitle,
'description':programDescription,
'url': url,
}
return info
def streamActive(self):
"""Returns a bool representing this stream is up or not"""
return self.streamtool.isStreaming()
def privateFolder(sectionBrain):
exclude_from_nav = getattr(sectionBrain, 'exclude_from_nav', True)
#any section included in navigation is public.
if exclude_from_nav == False:
return False
sectionObj = sectionBrain.getObject()
include_in_sitemap = getattr(sectionObj, 'include_in_sitemap', False)
#if section is set to show in sitemap (although not in nav) it's public
if include_in_sitemap == True:
return False
return True
def publicFolder(sectionBrain):
return not privateFolder(sectionBrain)