Ejemplo n.º 1
0
class ICalFile(FormatFile):
    _cal=None
    
    def __init__(self,name):
        filename=name+'.ics'
        super(ICalFile,self).__init__(filename)
        self._cal=Calendar()
        self._cal.add('prodid', '-//KPlato Export//athabascau.ca//')
        self._cal.add('version', '2.0')
    
    def add_appointment(self,uid,dtstart,dtend,dtstamp,summary,description):
        event=Event()
        event.add('summary',summary)
        event.add('description',description)
        event['uid']=uid

        # event.add('dtstart',dtstart)
        event['dtstart']=vDatetime(dtstart).ical()
        # event.add('dtend',dtend)
        event['dtend']=vDatetime(dtend).ical()
        # event.add('dtstamp',dtstamp)
        event['dtstamp']=vDatetime(dtstamp).ical()
        self._cal.add_component(event)
    
    def save(self):
        f=open(self.filename,'w')
        f.write(self._cal.as_string())
        f.close()
Ejemplo n.º 2
0
def view_instance_calendar(request, course_url, instance_url):
    """ 
    Renders a iCalendar feed for a CourseInstance. Unlike most other views in this module, this
    view does not require the user to be logged in.
    
    @param request: the Django HttpRequest object
    @param course_url: the url value of a Course object
    @param instance_url: the url value of a CourseInstance object 
    """
    
    course_instance = _get_course_instance(course_url, instance_url)
    
    cal = Calendar()
    
    cal.add('prodid', '-// A+ calendar //')
    cal.add('version', '2.0')
    
    for course_module in course_instance.course_modules.all():
        event = Event()
        event.add('summary', course_module.name)
        
        # FIXME: Currently all times added are the closing time.
        # The event will need to be longer than 0 seconds in order 
        # to be displayed clearly on calendar applications.
        event.add('dtstart', course_module.closing_time)
        event.add('dtend', course_module.closing_time)
        event.add('dtstamp', course_module.closing_time)
        
        event['uid'] = "module/" + str(course_module.id) + "/A+"
        
        cal.add_component(event)
    
    response = HttpResponse(cal.as_string(), content_type="text/calendar; charset=utf-8")
    return response
Ejemplo n.º 3
0
 def export_ics(self):
     events = Event.get_recent_past_and_future()
     url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
     cal = Calendar()
     for event in events:
         iev = CalendarEvent()
         iev.add('summary', event.name if event.status == 'approved' else event.name + ' (%s)' % event.status.upper())
         # make verbose description with empty fields where information is missing
         ev_desc = '__Status: %s\n__Member: %s\n__Type: %s\n__Estimated size: %s\n__Info URL: %s\n__Fee: %s\n__Contact: %s, %s\n__Rooms: %s\n\n__Details: %s\n\n__Notes: %s' % (
             event.status,
             event.owner(),
             event.type,
             event.estimated_size,
             event.url,
             event.fee,
             event.contact_name,
             event.contact_phone,
             event.roomlist(),
             event.details,
             event.notes)
         # then delete the empty fields with a regex
         ev_desc = re.sub(re.compile(r'^__.*?:[ ,]*$\n*',re.M),'',ev_desc)
         ev_desc = re.sub(re.compile(r'^__',re.M),'',ev_desc)
         ev_url = url_base + event_path(event)
         iev.add('description', ev_desc + '\n--\n' + ev_url)
         iev.add('url', ev_url)
         if event.start_time:
           iev.add('dtstart', event.start_time.replace(tzinfo=pytz.timezone('US/Pacific')))
         if event.end_time:
           iev.add('dtend', event.end_time.replace(tzinfo=pytz.timezone('US/Pacific')))
         cal.add_component(iev)
     return 'text/calendar', cal.as_string()
Ejemplo n.º 4
0
 def export_ics(self):
     events = Event.get_recent_past_and_future()
     url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
     cal = Calendar()
     for event in events:
         iev = CalendarEvent()
         iev.add('summary', event.name if event.status == 'approved' else event.name + ' (%s)' % event.status.upper())
         # make verbose description with empty fields where information is missing
         ev_desc = '__Status: %s\n__Member: %s\n__Type: %s\n__Estimated size: %s\n__Info URL: %s\n__Fee: %s\n__Contact: %s, %s\n__Rooms: %s\n\n__Details: %s\n\n__Notes: %s' % (
             event.status,
             event.owner(),
             event.type,
             event.estimated_size,
             event.url,
             event.fee,
             event.contact_name,
             event.contact_phone,
             event.roomlist(),
             event.details,
             event.notes)
         # then delete the empty fields with a regex
         ev_desc = re.sub(re.compile(r'^__.*?:[ ,]*$\n*',re.M),'',ev_desc)
         ev_desc = re.sub(re.compile(r'^__',re.M),'',ev_desc)
         ev_url = url_base + event_path(event)
         iev.add('description', ev_desc + '\n--\n' + ev_url)
         iev.add('url', ev_url)
         if event.start_time:
           iev.add('dtstart', event.start_time.replace(tzinfo=pytz.timezone('US/Pacific')))
         if event.end_time:
           iev.add('dtend', event.end_time.replace(tzinfo=pytz.timezone('US/Pacific')))
         cal.add_component(iev)
     return 'text/calendar', cal.as_string()
Ejemplo n.º 5
0
def view_instance_calendar(request, course_url, instance_url):
    """ 
    Renders a iCalendar feed for a CourseInstance. Unlike most other views in this module, this
    view does not require the user to be logged in.
    
    @param request: the Django HttpRequest object
    @param course_url: the url value of a Course object
    @param instance_url: the url value of a CourseInstance object 
    """

    course_instance = _get_course_instance(course_url, instance_url)

    cal = Calendar()

    cal.add('prodid', '-// A+ calendar //')
    cal.add('version', '2.0')

    for course_module in course_instance.course_modules.all():
        event = Event()
        event.add('summary', course_module.name)

        # FIXME: Currently all times added are the closing time.
        # The event will need to be longer than 0 seconds in order
        # to be displayed clearly on calendar applications.
        event.add('dtstart', course_module.closing_time)
        event.add('dtend', course_module.closing_time)
        event.add('dtstamp', course_module.closing_time)

        event['uid'] = "module/" + str(course_module.id) + "/A+"

        cal.add_component(event)

    response = HttpResponse(cal.as_string(),
                            content_type="text/calendar; charset=utf-8")
    return response
Ejemplo n.º 6
0
def sk_forum_planning_calendar(request):
    from datetime import datetime, date
    from icalendar import Calendar, Event, UTC, LocalTimezone # timezone
    cal = Calendar()
    cal.add('prodid', '-//SK Forum Calendar//killingar.net//')
    cal.add('version', '2.0')
    
    import MySQLdb
    connection = MySQLdb.connect(user='******', passwd='2oVGx8VwuqUfY', db='forum')
    cursor = connection.cursor()
    from django.utils.encoding import smart_unicode
    cursor.execute(u'SELECT id FROM users where name = "%s"' % (smart_unicode(request.REQUEST['username'])))
    userID = cursor.fetchall()[0]
    cursor.execute("select id, name, time, description from events, eventdata where events.id = eventdata.event and events.visible = 1 and eventdata.user = %s and eventdata.data in (1, 0)" % userID)
    rows = cursor.fetchall()
    for row in rows:
        id, name, time, description = row
        event = Event()
        event.add('summary', smart_unicode(name.decode('latin-1')))
        #event.add('dtstart', 'DATE:'+time.strftime("%Y%m%d"))
        #event.add('dtend', 'DATE:'+time.strftime("%Y%m%d"))
        event.add('dtstart', date(time.year, time.month, time.day))
        event.add('dtend', date(time.year, time.month, time.day))
        if description:
            event.add('description', smart_unicode(description.decode('latin-1')))
        #event.add('X-FUNAMBOL-ALLDAY', '')
        event['uid'] = 'planning/%[email protected]' % id
        event.add('priority', 5) # normal priority
    
        cal.add_component(event)
    connection.close()
    
    return HttpResponse(cal.as_string(), content_type='text/calendar')
Ejemplo n.º 7
0
 def XtestBla(self):
     from icalendar import Calendar
     c = Calendar()
     c['description']=u'Paragraph one\n\nParagraph two'
     output = c.as_string()
     self.assertEqual(output, 
             "BEGIN:VCALENDAR\r\nDESCRIPTION:Paragraph one\r\n \r\n Paragraph two\r\nEND:VCALENDAR\r\n")
Ejemplo n.º 8
0
def ical(request, type='Full'):
	"""
	"""
	cal = Calendar()
	site = Site.objects.get_current()
	
	if type.lower() == 'full':
		gigs = g.objects.all()
	else:
		gigs = g.objects.filter(date__gte=datetime.now())

	cal.add('prodid','-//{0} Events Calendar//{1}//EN'.format(type, site.domain))
	cal.add('version','2.0')

	for gig in gigs:
		performances = p.objects.filter(gig=gig.id)
		for performance in performances:
			start = datetime.strptime('{0} {1}'.format(gig.date, performance.time), "%Y-%m-%d %H:%M:%S")
			end = start + timedelta(hours=2)
			ical_event = Event()
			ical_event.add('summary','{0}, {1}, {2}'.format(gig.venue.name, gig.venue.city, gig.venue.state))
			ical_event.add('dtstart',start)
			ical_event.add('dtend',end)
			url = 'http://{0}{1}'.format(site.domain,gig.get_absolute_url())
			ical_event.add('description',url)
			cal.add_component(ical_event)

	response = HttpResponse(cal.as_string(), mimetype='text/calendar')
	response['Filename'] = 'filename.ics'
	response['Content-Disposition'] = 'attachment; filename=filename.ics'
	return response
Ejemplo n.º 9
0
 def new(self, cal, uri, event):
 
     if not cal:
     
         print "creating new calendar"
         cal = Calendar()
         cal['prodid'] = myProduct.prodid
         cal['version'] = myProduct.version
         
     if uri == "" or uri == None:
     
         import os
         uri = os.path.join(os.path.expanduser("~"),
                            ".gdesklets",
                            "gdesklets-calendar" + os.extsep + "ics")
         
         print "creating new file %s" % uri
     
     # Add the event to the calendar
     cal.add_component(event)
     
     try:
         tmp_cal_string = cal.as_string()
     except ValueError, error:
         print "ValueError in %s: \"%s\"\n" % (uri, error)
         print "This is a python issue, but could be solved in the icalendar package."
         print "Work around it by removing the offending dates in %s ." % uri
         return
Ejemplo n.º 10
0
    def get(self, format):
        events = Event.all().filter("status IN", ["approved", "canceled"]).order("start_time")
        if format == "ics":
            cal = Calendar()
            for event in events:
                cal.add_component(event.to_ical())
            self.response.headers["content-type"] = "text/calendar"
            self.response.out.write(cal.as_string())
        elif format == "json":
            self.response.headers["content-type"] = "application/json"
            events = map(lambda x: x.to_dict(summarize=True), Event.get_approved_list())
            self.response.out.write(simplejson.dumps(events))
        elif format == "rss":
            url_base = "http://" + self.request.headers.get("host", "events.hackerdojo.com")
            rss = PyRSS2Gen.RSS2(
                title="Hacker Dojo Events Feed",
                link=url_base,
                description="Upcoming events at the Hacker Dojo in Mountain View, CA",
                lastBuildDate=datetime.now(),
                items=[
                    PyRSS2Gen.RSSItem(
                        title=event.name,
                        link=url_base + event_path(event),
                        description=event.details,
                        guid=url_base + event_path(event),
                        pubDate=event.updated,
                    )
                    for event in events
                ],
            )

            self.response.headers["content-type"] = "application/xml"
            self.response.out.write(rss.to_xml())
Ejemplo n.º 11
0
def icalendar(native_languages, foreign_languages):
    calendar = calendar_for_languages(
        native_languages, foreign_languages)
    def full_names(langs):
        str = ", ".join([LANGUAGE_DICT(l) for l in langs[:-1]])
        if len(langs) > 1:
            str = " or ".join(str, langs[-1])
        return str
    cal = Calendar()
    calendar_description = \
        ("Dates where we have at least {0} speakers of "
         "{1} learning {2} scheduled to be online at langolab.com.").format(
        NOTIFICATION_PARTNER_THRESHOLD,
        full_names(foreign_languages), 
        full_names(native_languages))
    cal.add('prodid', '-//Langolab//langolab.com//EN')
    cal.add("version", "2.0")
    cal.add("X-WR-CALNAME", "Langolab Language Pairings")
    cal.add("X-WR-CALDESC", calendar_description)
    cal_ranges = calendar.languagecalendarrange_set.filter(
        end_date__gte=utcnow()).order_by('start_date')
    for cal_range in cal_ranges:
        event = Event()
        event.add('summary', 'Partners online at langolab.com')
        event.add('dtstart', cal_range.start_date)
        event.add('dtend', cal_range.end_date + timedelta(hours=1))
        event.add('dtstamp', utcnow())
        event['uid'] = cal_range.uid
        cal.add_component(event)
    return cal.as_string()
Ejemplo n.º 12
0
def schedule_user_bookmarks(request, user_id, user_hash):
    
    user = get_object_or_404(User, id=user_id)
    auth_hash = hash_for_user(user)
    
    if user_hash != auth_hash:
        raise Http404()
    
    bookmarks = UserBookmark.objects.filter(user=user)
    
    cal = Calendar()
    cal.add("prodid", "-//PyCon 2011 Bookmarks//us.pycon.org//EN")
    cal.add("version", "2.0")
    cal.add("method", "REQUEST")
    cal.add("calscale", "GREGORIAN")
    cal.add("X-WR-CALNAME", "PyCon 2011 Bookmarks - %s" % user.username)
    cal.add("X-WR-TIMEZONE","US/Eastern")
    
    for bookmark in bookmarks:
        p = bookmark.presentation
        if p.slot is not None:
            event = Event()
            event.add("summary", p.title)
            event.add("dtstart", p.slot.start)
            event.add("dtend", p.slot.end)
            event.add("dtstamp", datetime.datetime.utcnow())
            event.add("description", p.speaker.name + "\n\n" + p.description)
            event.add("location", p.slot.track)
            event["uid"] = str(p.pk) + "-2011.us.pycon.org"
            cal.add_component(event)
    
    response = HttpResponse(cal.as_string(), content_type="text/calendar")
    response["Content-Disposition"] = "filename=pycon2011-%s-bookmarks.ics" % user.username.encode("utf-8")
    return response
Ejemplo n.º 13
0
    def emit( self, serialization ):
        try:
            from icalendar import Calendar, Event
            from icalendar import vText
        except ImportError:
            raise SerializationError( "iCalendar module could not be loaded." )

        cal = Calendar()
        cal.add( 'prodid', '-//European Southern Observatory//Djangoplicity//EN' )
        cal.add( 'version', '2.0' )

        for e in serialization.data:
            event = Event()
            event.add( 'summary', smart_unicode( e['summary'] ) )
            event.add( 'description', smart_unicode( e['description'] ) )
            event.add( 'dtstart', e['dtstart'] )
            event.add( 'dtend', e['dtend'] )
            event.add( 'dtstamp', e['dtstamp'] )

            if 'location' in e:
                event['location'] = vText( smart_unicode( e['location'] ) )

            cal.add_component( event )

        return cal.as_string()
Ejemplo n.º 14
0
def export(request, event_id):
    event = get_model('events', 'event').objects.get(id=event_id)

    cal = Calendar()
    site = Site.objects.get_current()

    cal.add('prodid', '-//%s Events Calendar//%s//' % (site.name, site.domain))
    cal.add('version', '2.0')

    site_token = site.domain.split('.')
    site_token.reverse()
    site_token = '.'.join(site_token)

    ical_event = Event()
    ical_event.add('summary', event.description)
    ical_event.add('dtstart', event.start)
    ical_event.add('dtend', event.end and event.end or event.start)
    ical_event.add('dtstamp', event.end and event.end or event.start)
    ical_event['uid'] = '%d.event.events.%s' % (event.id, site_token)
    cal.add_component(ical_event)

    response = HttpResponse(cal.as_string(), mimetype="text/calendar")
    response[
        'Content-Disposition'] = 'attachment; filename=%s.ics' % event.slug
    return response
Ejemplo n.º 15
0
    def get(self, format):
        events = Event.all().filter('status IN', ['approved', 'canceled']).order('start_time')
        if format == 'ics':
            cal = Calendar()
            for event in events:
                cal.add_component(event.to_ical())
            self.response.headers['content-type'] = 'text/calendar'
            self.response.out.write(cal.as_string())
        elif format == 'json':
            self.response.headers['content-type'] = 'application/json'
            events = map(lambda x: x.to_dict(summarize=True), Event.get_approved_list())
            self.response.out.write(simplejson.dumps(events))
        elif format =='rss':
            url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
            rss = PyRSS2Gen.RSS2(
                title = "Hacker Dojo Events Feed",
                link = url_base,
                description = "Upcoming events at the Hacker Dojo in Mountain View, CA",
                lastBuildDate = datetime.now(),
                items = [PyRSS2Gen.RSSItem(
                            title = event.name,
                            link = url_base + event_path(event),
                            description = event.details,
                            guid = url_base + event_path(event),
                            pubDate = event.updated,
                         ) for event in events]
            )

            self.response.headers['content-type'] = 'application/xml'
            self.response.out.write(rss.to_xml())
Ejemplo n.º 16
0
    def export (self):
        """Export to ical format"""
        start_date = datetime.date(2011, 10, 30) # first sunday of semester
        
        cal = Calendar()
        cal.add("prodid", "-//NHY//Technion Students' Schedule 1.0//EN")
        cal.add("version", 2.0)

        for (day_num, activities) in enumerate(self):
            for (activity_num, activity) in enumerate(activities):
                # date and time
                date = start_date + datetime.timedelta(day_num)
                time = datetime.time(*self.split_slot(activity.start))
                dt_start = datetime.datetime.combine(date, time)
                
                time = datetime.time(*self.split_slot(activity.start + activity.length))
                dt_end = datetime.datetime.combine(date, time)

                # add event to calendar file
                event = Event()
                event.add("summary", activity.text)
                event.add("dtstart", dt_start)
                event.add("dtend", dt_end)
                event.add("dtstamp", datetime.datetime.today())
                event["uid"] = "NHY-TECHNION-STUDENTS-SCHEDULE-%d%d" % (day_num, activity_num)
                cal.add_component(event)

        f = open(os.path.expanduser("~/test.ics"), "w")
        f.write(get_display(cal.as_string())) 
        #f.write((cal.as_string())) 
        f.close()
Ejemplo n.º 17
0
 def get(self, format):
     if format == 'ics':
         events = Event.all().filter('status IN', ['approved', 'canceled']).order('start_time')
         cal = Calendar()
         for event in events:
             cal.add_component(event.to_ical())
         self.response.headers['content-type'] = 'text/calendar'
         self.response.out.write(cal.as_string())
Ejemplo n.º 18
0
def genAllEventsCalendar( cal_file ):
	cal = Calendar()
	cal.add('prodid', '-//calgen.py//xmpp.org//')
	cal.add('version', '2.0')
	for event in allevents:
		cal.add_component(event)
	
	f = open( cal_file , 'wb')
	f.write(cal.as_string())
	f.close()
Ejemplo n.º 19
0
    def render(self):
        viewer = INewsViewer(self.context, None)
        factory = getMultiAdapter((self.content, self.request), IEvent)

        cal = Calendar()
        cal.add('prodid', '-//Silva News Calendaring//lonely event//')
        cal.add('version', '2.0')
        for event in factory(viewer):
            cal.add_component(event)
        return cal.as_string()
Ejemplo n.º 20
0
def genAllEventsCalendar(cal_file):
    cal = Calendar()
    cal.add('prodid', '-//calgen.py//xmpp.org//')
    cal.add('version', '2.0')
    for event in allevents:
        cal.add_component(event)

    f = open(cal_file, 'wb')
    f.write(cal.as_string())
    f.close()
Ejemplo n.º 21
0
 def get(self, format):
     events = Event.all().filter('status IN', ['approved', 'canceled']).order('start_time')
     url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
     if format == 'json':
         self.response.headers['content-type'] = 'application/json'
         events = map(lambda x: x.to_dict(summarize=True), Event.get_approved_list())
         self.response.out.write(simplejson.dumps(events))
     elif format == 'ics':
             cal = Calendar()
             for event in events:
                 iev = CalendarEvent()
                 iev.add('summary', event.name if event.status == 'approved' else event.name + ' (%s)' % event.status.upper())
                 # make verbose description with empty fields where information is missing
                 ev_desc = '__Status: %s\n__Member: %s\n__Type: %s\n__Estimated size: %s\n__Info URL: %s\n__Fee: %s\n__Contact: %s, %s\n__Rooms: %s\n\n__Details: %s\n\n__Notes: %s' % (
                     event.status, 
                     event.owner(), 
                     event.type, 
                     event.estimated_size, 
                     event.url, 
                     event.fee, 
                     event.contact_name, 
                     event.contact_phone, 
                     event.roomlist(), 
                     event.details, 
                     event.notes)
                 # then delete the empty fields with a regex
                 ev_desc = re.sub(re.compile(r'^__.*?:[ ,]*$\n*',re.M),'',ev_desc)
                 ev_desc = re.sub(re.compile(r'^__',re.M),'',ev_desc)
                 ev_url = url_base + event_path(event)
                 iev.add('description', ev_desc + '\n--\n' + ev_url)
                 iev.add('url', ev_url)
                 if event.start_time:
                   iev.add('dtstart', event.start_time.replace(tzinfo=pytz.timezone('US/Pacific')))
                 if event.end_time:
                   iev.add('dtend', event.end_time.replace(tzinfo=pytz.timezone('US/Pacific')))
                 cal.add_component(iev)
             self.response.headers['content-type'] = 'text/calendar'
             self.response.out.write(cal.as_string())
     elif format =='rss':
         url_base = 'http://' + self.request.headers.get('host', 'events.hackerdojo.com')
         rss = PyRSS2Gen.RSS2(
             title = "Hacker Dojo Events Feed",
             link = url_base,
             description = "Upcoming events at the Hacker Dojo in Mountain View, CA",
             lastBuildDate = datetime.now(),
             items = [PyRSS2Gen.RSSItem(
                         title = event.name,
                         link = url_base + event_path(event),
                         description = event.details,
                         guid = url_base + event_path(event),
                         pubDate = event.updated,
                         ) for event in events]
         )
         self.response.headers['content-type'] = 'application/xml'
         self.response.out.write(rss.to_xml())
Ejemplo n.º 22
0
def user_ics(request, username, user_feed_hash):
    host = request.META['HTTP_HOST']
    current_user, message = get_current_user(username)
    if message:
        return HttpResponseRedirect(reverse('home'))

    #user_events = Event.objects.all()
    if not user_feed_hash == current_user.user_feed_hash:
        return HttpResponseRedirect(
            reverse('euser_user_view',
                    kwargs={'username': current_user.username}))

    user_events = Event.objects.filter(
        attendee__in=current_user.attendee_set.all()).order_by('-event_date')
    userical = Calendar()

    userical['summary'] = "Calendar for user %s" % (current_user.username)
    userical.add('prodid', '-//Evesch//NONSGML v1.0//EN')
    userical.add('version', '2.0')

    for event in user_events:
        cal_event = icalendar.Event()
        cal_event.add('summary', event.event_name)
        cal_event.add('dtstart', event.event_date)
        cal_event.add('description', event.event_desc)
        cal_event.add('categories', event.event_type)
        cal_event.add('duration', timedelta(hours=1))
        cal_event.add(
            'url', "http://" + host +
            reverse('event_event_view',
                    kwargs={
                        'org_short_name': event.event_org.org_short_name,
                        'event_hash': event.event_hash,
                    }))
        if event.event_creator_name.email:
            organizer_n = event.event_creator_name.email
        else:
            organizer_n = "%s %s" % (event.event_creator_name.first_name,
                                     event.event_creator_name.last_name)
        organizer = vCalAddress('MAILTO:' + organizer_n)
        organizer.params['cn'] = vText("%s %s" %
                                       (event.event_creator_name.first_name,
                                        event.event_creator_name.last_name))
        organizer.params['role'] = vText('CREATOR')
        cal_event.add('organizer', organizer, encode=0)
        userical.add_component(cal_event)

    template_name = "core/message.html"
    context = {}

    response = HttpResponse()
    response['Content-Type'] = 'text/calendar'
    response.write(userical.as_string())
    #template_name = "error.html"
    return response
Ejemplo n.º 23
0
 def to_ics(self):
     if not os.path.exists(self.storagedir):
         os.makedirs(self.storagedir)
     cal = Calendar()
     cal.add('version', '2.0')
     cal.add(
         'prodid',
         '-//A.P.U Timetable Synchronizer by MavJS// http://goog.gl/9FRHL //'
     )
     final_html = self.scrape()
     for row in final_html.findAll('tr')[1:]:
         event = Event()
         col = row.findAll('td')
         date = col[0].font.string
         time = col[1].font.string
         classroom = col[2].font.string
         location = col[3].font.string
         subject = col[4].font.string
         lecturer = col[5].font.string
         record = (date, time, classroom, location, subject, lecturer)
         line = "|".join(record)
         #this is lot of unesswary work i know but i like it this way feel free to edit
         parts = line.split('|')
         #trying to find the time
         times = parts[1].split(' - ')
         title = parts[4]
         where = parts[2] + "\t" + parts[3]
         content = parts[5]
         begin_str = "%s %s:00" % (parts[0][4:].strip(""), times[0])
         end_str = "%s %s:00" % (parts[0][4:].strip(""), times[1])
         now = datetime.now()
         now_time = now.strftime('%Y%m%dT%H%M%SZ')
         begin_time = datetime.strptime(
             begin_str, '%d-%b-%y %H:%M:%S').strftime('%Y%m%dT%H%M%SZ')
         end_time = datetime.strptime(
             end_str, '%d-%b-%y %H:%M:%S').strftime('%Y%m%dT%H%M%SZ')
         #start gathering info for VEVENT
         summary = title + " by " + content + " at " + where
         desc = title
         start = begin_time
         end = end_time
         stamp = now_time
         event.add('dtstart', start, encode=0)
         event.add('dtend', end, encode=0)
         event.add('transp', 'TRANSPARENT')
         event.add('summary', summary)
         event.add('description', desc)
         event['uid'] = hashlib.md5(desc).hexdigest()
         event.add('dtstamp', stamp, encode=0)
         cal.add_component(event)
     f = file(self.saveics, 'wb')
     f.write(cal.as_string())
     f.close()
     return self.saveics
Ejemplo n.º 24
0
def genExtensionsCalendar(cal_file):
    cal = Calendar()
    cal.add('prodid', '-//calgen.py//xmpp.org//')
    cal.add('version', '2.0')
    files = glob.glob('extensions/xep-????.xml')
    files.sort(key=lambda x: x.lower())
    for file in files:
        parseXEP(cal, file)

    f = open(cal_file, 'wb')
    f.write(cal.as_string())
    f.close()
Ejemplo n.º 25
0
def genExtensionsCalendar( cal_file ):
	cal = Calendar()
	cal.add('prodid', '-//calgen.py//xmpp.org//')
	cal.add('version', '2.0')
	files = glob.glob('extensions/xep-????.xml')
	files.sort(key=lambda x: x.lower())
	for file in files:
		parseXEP( cal, file)
	
	f = open( cal_file , 'wb')
	f.write(cal.as_string())
	f.close()
Ejemplo n.º 26
0
 def exportToICal(self, event_id):
   from pyamf.remoting.client import RemotingService  # @UnresolvedImport
   from icalendar import Calendar, Event, vDatetime  # @UnresolvedImport
   import uuid, os
   
   client = RemotingService(self.application.app_settings["url"]+"/"+self.application.app_config["connection"]["npi_service"])
   service = client.getService("default")
   
   events = service.loadTable_amf(self.getCredentials(), "models.event", "id="+str(event_id), None)
   if events.__class__.__name__!="ArrayCollection": 
     wx.MessageBox(str(events), "saveDataSet", wx.OK | wx.ICON_ERROR)
     return
   elif len(events)>0:
     event = events[0]
           
     cal = Calendar()
     cal.add('prodid', '-//nervatura.com/NONSGML Nervatura Calendar//EN')
     cal.add('version', '2.0')
     clevent = Event()
     if event["uid"]!=None:
       clevent['uid'] = event["uid"]
     else:
       clevent['uid'] = uuid.uuid4()
     if event["fromdate"]!=None:
       clevent['dtstart'] = vDatetime(event["fromdate"]).ical()
     if event["todate"]!=None:
       clevent['dtend'] = vDatetime(event["todate"]).ical()  
     if event["subject"]!=None:
       clevent['summary'] = event["subject"]
     if event["place"]!=None:
       clevent['location'] = event["place"]
     if event["eventgroup"]!=None:
       groups = service.loadTable_amf(self.getCredentials(), "models.groups", "id="+str(event["eventgroup"]), None)
       if groups.__class__.__name__=="ArrayCollection":
         if len(groups)>0:
           clevent['category'] = groups[0].groupvalue
     if event["description"]!=None:
       clevent['description'] = event["description"]  
     cal.add_component(clevent)
     
     wildcard = "iCal files (*.ical)|"     \
          "All files (*.*)|*.*"
     dlg = wx.FileDialog(
           self, message="Event export", 
           defaultDir=(os.getenv('USERPROFILE') or os.getenv('HOME')), 
           defaultFile=str(event["calnumber"]).replace("/", "_"), wildcard=wildcard, style=wx.SAVE)
     dlg.SetFilterIndex(0)
     if dlg.ShowModal() == wx.ID_OK:
       icalfile = open(dlg.GetPath()+".ical", 'w')
       icalfile.write(cal.as_string())
       icalfile.close()
     dlg.Destroy()
Ejemplo n.º 27
0
def main():
    """
    Perform iCalendar to hCalendar rendering.
    """
    html_dir = len(sys.argv) > 1 and sys.argv[1] or 'hcal'
    ics_fout = len(sys.argv) > 2 and open(sys.argv[2], 'w') or sys.stdout

    # Parse a directory of HTML files for hCalendar events.
    hp = HCalendarParser()
    events = []
    for dirpath, dirnames, filenames in os.walk(html_dir):
        for fn in filenames:
            if fn.endswith(".html") or fn.endswith(".htm"):
                fp = os.path.join(dirpath, fn)
                data = open(fp, 'r').read()
                events.extend(hp.parse(data))

    # Build a calendar from the parsed events and print the data
    cal = Calendar()
    for e in events:
        cal.add_component(e)
    print cal.as_string()
Ejemplo n.º 28
0
def main():
    scr = SupercinemaRoveretoEventReader(True)
    events = scr.get_events()
    
    cal = Calendar()
    #cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    for event in events:
        cal.add_component(event)
    
    f = open('scr.ics', 'wb')
    f.write(cal.as_string())
    f.close()
Ejemplo n.º 29
0
def main():
    """
    Perform iCalendar to hCalendar rendering.
    """
    html_dir = len(sys.argv) > 1 and sys.argv[1] or 'hcal'
    ics_fout = len(sys.argv) > 2 and open(sys.argv[2], 'w') or sys.stdout

    # Parse a directory of HTML files for hCalendar events.
    hp = HCalendarParser()
    events = []
    for dirpath, dirnames, filenames in os.walk(html_dir):
        for fn in filenames:
            if fn.endswith(".html") or fn.endswith(".htm"):
                fp   = os.path.join(dirpath, fn)
                data = open(fp, 'r').read()
                events.extend(hp.parse(data))
    
    # Build a calendar from the parsed events and print the data
    cal = Calendar()
    for e in events: 
        cal.add_component(e)
    print cal.as_string()
Ejemplo n.º 30
0
def index(request, employee):
    trips = travelcal.Traveler.objects.get(traveler=employee).Trip()
    cal = Calendar()
    for trip in trips:
        ical_event = Event()
        ical_event.add('summary', '')
        ical_event.add('dtstart', '')
        ical_event.add('dtend', '')
        ical_event.add('dtstamp', '')
        cal.add_component(ical_event)
    response = HttpResponse(cal.as_string(), mimetype="text/calendar")
    response[
        'Content-Disposition'] = 'attachment; filename=%s.ics' % employee.slug
    return response
Ejemplo n.º 31
0
def genCalendarFromEventsFile( events_file, cal_file ):
	try:
		events = SimpleEvents( events_file )
		cal = Calendar()
		cal.add('prodid', '-//calgen.py//xmpp.org//')
		cal.add('version', '2.0')
		day = timedelta(days=1)
	
		for ev in events.getEventList():
			event = Event()
			if "date" in ev:
				ev["date"] = ev["date"].rstrip("Z")
			
			if "all-day" in ev:
				start = datetime.strptime(ev["date"], "%Y-%m-%d") # T%H:%M:%S
				event.add('dtstart', start.date())
				event.add('dtend', (start + day).date())
				event.add("dtstamp", (start + day).date())
			else:
				start = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
				start = start.replace(tzinfo=UTC)
				duration = timedelta(minutes=int(ev["duration"]))
				event.add('dtstart', start)
				event.add('dtend', (start + duration))
				event.add("dtstamp", (start + duration))
			if "alarm" in ev:
				alarm = Alarm()
				alarm_time = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
				alarm_time = alarm_time.replace(tzinfo=UTC)
				alarm_time = alarm_time - timedelta(minutes=15)
				alarm.add("trigger", alarm_time)
				alarm.add("action", "display")
				event.add_component(alarm)
			if "summary" in ev:
				event.add('summary', ev["summary"])
			if "description" in ev:
				event.add('description', ev["description"])
			if "url" in ev:
				event.add('url', ev["url"])
			
			cal.add_component(event)
			allevents.append(event)
	
		f = open( cal_file , 'wb')
		f.write(cal.as_string())
		f.close()
	except:
		print "File not found! - " + events_file
		print "Unexpected error:", sys.exc_info()[0]
		traceback.print_exc(file=sys.stdout)
Ejemplo n.º 32
0
def genCalendarFromEventsFile(events_file, cal_file):
    try:
        events = SimpleEvents(events_file)
        cal = Calendar()
        cal.add('prodid', '-//calgen.py//xmpp.org//')
        cal.add('version', '2.0')
        day = timedelta(days=1)

        for ev in events.getEventList():
            event = Event()
            if "date" in ev:
                ev["date"] = ev["date"].rstrip("Z")

            if "all-day" in ev:
                start = datetime.strptime(ev["date"], "%Y-%m-%d")  # T%H:%M:%S
                event.add('dtstart', start.date())
                event.add('dtend', (start + day).date())
                event.add("dtstamp", (start + day).date())
            else:
                start = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
                start = start.replace(tzinfo=UTC)
                duration = timedelta(minutes=int(ev["duration"]))
                event.add('dtstart', start)
                event.add('dtend', (start + duration))
                event.add("dtstamp", (start + duration))
            if "alarm" in ev:
                alarm = Alarm()
                alarm_time = datetime.strptime(ev["date"], "%Y-%m-%dT%H:%M:%S")
                alarm_time = alarm_time.replace(tzinfo=UTC)
                alarm_time = alarm_time - timedelta(minutes=15)
                alarm.add("trigger", alarm_time)
                alarm.add("action", "display")
                event.add_component(alarm)
            if "summary" in ev:
                event.add('summary', ev["summary"])
            if "description" in ev:
                event.add('description', ev["description"])
            if "url" in ev:
                event.add('url', ev["url"])

            cal.add_component(event)
            allevents.append(event)

        f = open(cal_file, 'wb')
        f.write(cal.as_string())
        f.close()
    except:
        print "File not found! - " + events_file
        print "Unexpected error:", sys.exc_info()[0]
        traceback.print_exc(file=sys.stdout)
Ejemplo n.º 33
0
class Scheduler():
    def __init__(self, ical_string, start_date, end_date, new_events):
        self.ical = Calendar.from_string(ical_string)
        self.simpl_ical = Calendar()
        self.new_events = new_events
        self.new_events.sort(key=lambda x: x.duration, reverse=True)
        self.start_date = start_date - start_date%30 + 30
        self.end_date = end_date - end_date%30 + 30

    def findSchedule(self):
        for event in self.new_events:
           is_scheduled = False
           curr_time = self.end_date - event.duration
           while not is_scheduled and not curr_time < self.start_date:
               event.start = curr_time
               event.end = curr_time + event.duration
               is_valid = True
               # check conflicts with current schedule
               for component in self.ical.walk():
                   if component.name == 'VEVENT':
                       #try:
                       dc = component.decoded
                       dtstart = time.mktime(time.strptime(str(dc('dtstart')), '%Y-%m-%d %H:%M:%S+00:00'))/60
                       dtend = time.mktime(time.strptime(str(dc('dtend')), '%Y-%m-%d %H:%M:%S+00:00'))/60
                       if curr_time > dtstart and curr_time < dtend or curr_time + event.duration > dtstart and curr_time + event.duration < dtend or curr_time < dtstart and curr_time + event.duration > dtend or curr_time > dtstart and curr_time + event.duration < dtend or curr_time == dtstart or curr_time + event.duration == dtend:
                           is_valid = False
                           break
               if is_valid:
                   for constraint in event.constraints:
                       if not constraint.isValid(event, self.ical):
                           is_valid = False
                           break
               if is_valid:
                   self.addToCalendar(event)
                   is_scheduled = True
               else:
                   curr_time -= 30

    def addToCalendar(self, event):
        e = Event()
        e['summary'] = event.summary
        e['dtstart'] = datetime.fromtimestamp(event.start*60).strftime('%Y%m%dT%H%M%SZ')
        e['dtend'] = datetime.fromtimestamp(event.end*60).strftime('%Y%m%dT%H%M%SZ')
        e['details'] = event.details
        self.ical.add_component(e)
        self.simpl_ical.add_component(e)

    def writeFile(self):
    	#return self.ical.as_string()
	return self.simpl_ical.as_string()
Ejemplo n.º 34
0
 def to_ics(self):
     if not os.path.exists(self.storagedir):
         os.makedirs(self.storagedir)
     cal = Calendar()
     cal.add('version', '2.0')
     cal.add('prodid', '-//A.P.U Timetable Synchronizer by MavJS// http://goog.gl/9FRHL //')
     final_html = self.scrape()
     for row in final_html.findAll('tr')[1:]:
         event = Event()
         col = row.findAll('td')
         date = col[0].font.string
         time = col[1].font.string
         classroom = col[2].font.string
         location = col[3].font.string
         subject = col[4].font.string
         lecturer = col[5].font.string
         record = (date, time, classroom, location, subject, lecturer)
         line = "|".join(record)
         #this is lot of unesswary work i know but i like it this way feel free to edit
         parts = line.split('|')
         #trying to find the time
         times = parts[1].split(' - ')
         title = parts[4]
         where = parts[2] + "\t" + parts[3]
         content = parts[5]
         begin_str = "%s %s:00" % (parts[0][4:].strip(""), times[0])
         end_str = "%s %s:00" % (parts[0][4:].strip(""), times[1])
         now = datetime.now()
         now_time = now.strftime('%Y%m%dT%H%M%SZ')
         begin_time = datetime.strptime(begin_str, '%d-%b-%y %H:%M:%S').strftime('%Y%m%dT%H%M%SZ')
         end_time = datetime.strptime(end_str, '%d-%b-%y %H:%M:%S').strftime('%Y%m%dT%H%M%SZ')
         #start gathering info for VEVENT
         summary = title + " by " + content + " at " + where
         desc = title
         start = begin_time
         end = end_time
         stamp = now_time
         event.add('dtstart', start, encode=0)
         event.add('dtend', end, encode=0)
         event.add('transp', 'TRANSPARENT')
         event.add('summary', summary)
         event.add('description', desc)
         event['uid'] = hashlib.md5(desc).hexdigest()
         event.add('dtstamp', stamp, encode=0)
         cal.add_component(event)
     f = file(self.saveics, 'wb')
     f.write(cal.as_string())
     f.close()
     return self.saveics
Ejemplo n.º 35
0
def orarender(beolvasott):
    cal = Calendar()
    cal.add("version", "2.0")
    cal.add("prodid", "-//Orarender//bergengocia.net//")
    cal["summary"] = beolvasott[0]
    cal["X-WR-CALNAME"] = beolvasott[0]
    print beolvasott[1]
    for ora in beolvasott[1]:
        cal.add_component(kurzusize(ora["nap"], idopontize(ora["ido"]), ora["hely"], ora["kurzus"]))
    #  import tempfile, os
    #  directory = tempfile.mkdtemp()
    #  f = open('/home/gazs/Desktop/orarend.ics', 'wb')
    #  f.write(cal.as_string())
    #  f.close()
    return cal.as_string(), beolvasott
Ejemplo n.º 36
0
 def GenerateEvent(self, _event):
     cal = Calendar()
     cal.add('prodid', '-//My calendar product//mxm.dk//')
     cal.add('version', '2.0')
     
     event = Event()
     event.add('summary', _event['summary'])
     event.add('dtstart', datetime.strptime(_event['start']['date'], "%Y-%m-%d"))
     event.add('dtend', datetime.strptime(_event['end']['date'], "%Y-%m-%d"))
     event.add('priority', 1)
     cal.add_component(event)
     self.set_header ('Content-Type', 'text/calendar')
     self.set_header ('Content-Disposition', 'attachment; filename=myCalendar.ics')
     self.write(cal.as_string())
     self.finish()
Ejemplo n.º 37
0
 def delete(self, cal, uri, uid):
 
     for c in cal.walk('VCALENDAR'):
     
         new_cal = Calendar()
         new_cal['prodid'] = c.decoded('prodid', myProduct.prodid)
         new_cal['version'] = c.decoded('version', myProduct.version)
         # The old calendar's properties have to be added manually
         # since the Calendar() constructor seems to generate a
         # vCalendar already.
         # That, and without the following edit of cal.walk(),
         # new_cal would've given us a calendar within a calendar
         for k in c.keys():
             new_cal.add(k, c[k])
         # First we need to find an event in self.__cal with the
         # given uid
         # But not all components are vEvents and not all vEvents
         # necessarily have 'uid' (maybe)
         for component in [n for n in c.walk() if c.name != 'VCALENDAR']:
         
             try:
                 if component.name == 'VEVENT' and component['uid'] == uid:
                     # Delete this one (in other words, don't add it)
                     print "Deleting %s" % component['summary']
                 else:
                     new_cal.add_component(component)
             except:
                 new_cal.add_component(component)
         
         # Maybe this isn't absolutely necessary
         # Maybe gamin file monitoring could be disabled during
         # this file write as well
         #TODO: investigate
         try:
             f = open(uri, 'wb')
         except:
             print "failed to open file %s" % uri
             return False
         else:
             try:
                 f.write(new_cal.as_string())
             except:
                 print "failed to write calendar or failed to convert it to a string"
                 return False
             else:
                 f.close()
     
     return True
	def render(self, request):
		data = self.construct()
		cal = Calendar()
		
		cal.add('prodid', 'iCalendar Feed')
		cal.add('version', '1.0')
		for newevent in data:
			ical_event = calEvent()
			ical_event.add('summary', newevent['description'])
			for occurrence in newevent['event_time']:
				ical_event.add('dtstart', occurrence['start_date'])
				ical_event.add('dtend', occurrence['end_date'])
			ical_event['uid'] = newevent['id']
			cal.add_component(ical_event)

			return cal.as_string()
Ejemplo n.º 39
0
def journeys(request):
    new_events = []
    if request.POST and 'plan' in request.POST:
        origin = request.session.pop('origin')
        events = request.session.pop('events')
        cal = Calendar()
        for i, event in enumerate(events):
            if request.POST.get('cb_%s' % str(i + 1)):
                ev = create_journey(origin, event)
                if ev:
                    cal.add_component(ev)
                    new_events.append({
                        'departure':
                        to_local(parse(str(ev['dtstart']))),
                        'arrival':
                        to_local(parse(str(ev['dtend']))),
                        'name':
                        ev['summary']
                    })

        # if not empty
        if cal.subcomponents:

            if request.POST.get('email'):
                address = request.POST.get('email_address')
                evs = len(new_events)
                title = "%s events" % evs if evs >= 2 else new_events[0]['name']
                generate_soap(address, cal, title)

                return HttpResponse('Email sent!')

            else:
                calfilename = 'calfile/meetit-%s.ics' % int(time.time())
                calfile = os.path.join(settings.MEDIA_ROOT, calfilename)

                f = open(calfile, 'wb')
                f.write(cal.as_string())
                f.close()

        else:
            cal_display = "no events!"

        return render_to_response('base_journeys.html', locals())

    else:
        return HttpResponseRedirect('/')
Ejemplo n.º 40
0
    def GenerateEvent(self, _event):
        cal = Calendar()
        cal.add('prodid', '-//My calendar product//mxm.dk//')
        cal.add('version', '2.0')

        event = Event()
        event.add('summary', _event['summary'])
        event.add('dtstart',
                  datetime.strptime(_event['start']['date'], "%Y-%m-%d"))
        event.add('dtend', datetime.strptime(_event['end']['date'],
                                             "%Y-%m-%d"))
        event.add('priority', 1)
        cal.add_component(event)
        self.set_header('Content-Type', 'text/calendar')
        self.set_header('Content-Disposition',
                        'attachment; filename=myCalendar.ics')
        self.write(cal.as_string())
        self.finish()
Ejemplo n.º 41
0
def user_ics(request,username,user_feed_hash):
    host = request.META['HTTP_HOST']
    current_user, message = get_current_user(username)
    if message:
        return HttpResponseRedirect(reverse('home'))

    #user_events = Event.objects.all()
    if not user_feed_hash == current_user.user_feed_hash:
        return HttpResponseRedirect(reverse('euser_user_view', kwargs={'username':current_user.username}))
    
    user_events =  Event.objects.filter(attendee__in=current_user.attendee_set.all()).order_by('-event_date')
    userical = Calendar()

    userical['summary'] = "Calendar for user %s" % (current_user.username)
    userical.add('prodid', '-//Evesch//NONSGML v1.0//EN')
    userical.add('version', '2.0')

    for event in user_events:
        cal_event = icalendar.Event()
        cal_event.add('summary', event.event_name)
        cal_event.add('dtstart', event.event_date)
        cal_event.add('description', event.event_desc)
        cal_event.add('categories',event.event_type)
        cal_event.add('duration',timedelta(hours=1))
        cal_event.add('url',"http://" + host + reverse('event_event_view',kwargs={'org_short_name':event.event_org.org_short_name,'event_hash':event.event_hash,}))
        if event.event_creator_name.email:
            organizer_n = event.event_creator_name.email
        else:
            organizer_n = "%s %s" % (event.event_creator_name.first_name, event.event_creator_name.last_name)
        organizer = vCalAddress('MAILTO:' + organizer_n)
        organizer.params['cn'] = vText("%s %s" % (event.event_creator_name.first_name, event.event_creator_name.last_name))
        organizer.params['role'] = vText('CREATOR')
        cal_event.add('organizer', organizer, encode=0)
        userical.add_component(cal_event)

    template_name = "core/message.html"
    context = {}
    
    response = HttpResponse()
    response['Content-Type'] = 'text/calendar'
    response.write(userical.as_string())
    #template_name = "error.html"
    return response
    
Ejemplo n.º 42
0
def for_zip(request, location):
    url = BASE_WEATHER_URL % location
    dom = minidom.parse(urllib.urlopen(url))
    forecasts = []

    link = dom.getElementsByTagName('link')
    url = link[0].childNodes[0].data


    for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'):
        forecasts.append({
            'date': node.getAttribute('date'),
            'low': node.getAttribute('low'),
            'high': node.getAttribute('high'),
            'condition_code': node.getAttribute('code'),
            'condition': node.getAttribute('text')
        })

    cal = Calendar()
    cal.add('prodid', '-//django-iweathercal//camronflanders.com//')
    cal.add('version', '2.0')

    for forecast in forecasts:
        parsed_date = re.search("(\d{2})\s(\w{3})\s(\d{4})", forecast['date'])

        day = int(parsed_date.group(1))
        month = int(MONTHS_TO_NUM['%s' % parsed_date.group(2).upper()])
        year = int(parsed_date.group(3))

        startdate = date(year, month, day)
        enddate = date(year, month, day) + timedelta(1)

        e = Event()
        e.add('summary', u'%s %s, %s\u00B0/%s\u00B0' % (CONDITION_CODES[forecast['condition_code']], forecast['condition'], forecast['high'], forecast['low']))
        e.add('dtstart', startdate)
        e.add('dtend', enddate)
        e.add('dtstamp', datetime.now())
        e.add('url', url)

        cal.add_component(e)

    response = HttpResponse(mimetype="text/calendar")
    response.write(cal.as_string())
    return response
    def ausgabe_ics(self, dn):
        print "Ausgabe von ", dn
        cal = Calendar()
        cal.add("prodid", "-//wnfDesktopKalender//wlsoft.de//")
        cal.add("version", "2.0")

        event = Event()
        event.add("summary", "Python meeting about calendaring")
        event.add("dtstart", wnf_tools.strToDate("03.04.2009"))
        event.add("dtend", wnf_tools.strToDate("03.04.2009"))
        event.add("dtstamp", wnf_tools.strToDate("03.04.2009"))
        event["uid"] = "20050115T101010/[email protected]"
        event.add("priority", 5)

        cal.add_component(event)

        f = open(dn, "wb")
        f.write(cal.as_string())
        f.close()
Ejemplo n.º 44
0
def schedule_user_bookmarks(request, user_id, user_hash):

    user = get_object_or_404(User, id=user_id)
    auth_hash = hash_for_user(user)

    if user_hash != auth_hash:
        raise Http404()

    bookmarks = UserBookmark.objects.filter(user=user)

    cal = Calendar()
    cal.add("prodid", "-//PyCon 2011 Bookmarks//us.pycon.org//EN")
    cal.add("version", "2.0")
    cal.add("method", "REQUEST")
    cal.add("calscale", "GREGORIAN")
    cal.add("X-WR-CALNAME", "PyCon 2011 Bookmarks - %s" % user.username)
    cal.add("X-WR-TIMEZONE", "US/Eastern")

    for bookmark in bookmarks:
        p = bookmark.presentation
        if p.slot is not None:
            event = Event()
            event.add("summary", p.title)
            event.add("dtstart", p.slot.start)
            event.add("dtend", p.slot.end)
            event.add("dtstamp", datetime.datetime.utcnow())
            event.add("description", p.speaker.name + "\n\n" + p.description)
            event.add("location", p.slot.track)
            event["uid"] = str(p.pk) + "-2011.us.pycon.org"
            cal.add_component(event)

    response = HttpResponse(cal.as_string(), content_type="text/calendar")
    response[
        "Content-Disposition"] = "filename=pycon2011-%s-bookmarks.ics" % user.username.encode(
            "utf-8")
    return response
Ejemplo n.º 45
0
DATE_FORMAT = "%a, %d %b %Y %H:%M:%S GMT"

feed = feedparser.parse("http://www.co.frederick.va.us/fredcocal.xml")

cal = Calendar()
cal.add('VERSION', '2.0')
cal.add('PRODID', 'feed2ical 0.1')
cal.add('X-WR-CALNAME;VALUE=TEXT', feed.channel.title)
cal.add('X-WR-CALDESC;VALUE=TEXT', feed.channel.description)

for item in feed['items']:

    event_date = datetime.strptime(item.caldate,
                                   DATE_FORMAT).replace(tzinfo=LocalTimezone())
    published_date = datetime.strptime(
        item.updated, DATE_FORMAT).replace(tzinfo=LocalTimezone())

    event = Event()
    event.add('UID', item.guid)
    event.add('SUMMARY', item.title)
    event.add('DESCRIPTION', item.description)
    event.add('URL;VALUE=URI', item.link)
    event.add('DTSTART', event_date.date())
    event.add('DTEND', event_date.date())
    event.add('DTSTAMP', published_date)

    cal.add_component(event)

sys.stdout.write(cal.as_string())
Ejemplo n.º 46
0
    def process_item(self, item, spider):
        cal = Calendar()
        cal.add('calscale', 'GREGORIAN')
        cal.add('version', '2.0')
        cal['method'] = 'PUBLISH'
        if item['exam'] != 'null':
            exam = Event()
            exam.add('summary',
                     '%s exam %s' % (item['code'], item['exam']['time']))
            starttime = datetime.combine(
                item['exam']['date'],
                time() if item['exam']['time'] == 'AM' else time(
                    12, 0)).replace(tzinfo=SGT())

            setstartend(exam, starttime, starttime + 12 * hour)
            cal.add_component(exam)

        if item['lecture_time_table'] != 'null':
            for l in item['lecture_time_table']:
                for lec in l['sessions']:
                    dow = lec['day']
                    ts = int(lec['starttime'])
                    te = int(lec['endtime'])
                    ts_hr, ts_min = ts / 100, ts % 100
                    te_hr, te_min = te / 100, te % 100

                    combstr = ','.join([
                        str(WEEK2ACTUAL[i - 1] + startweek - 1)
                        for i in lec['occurence']
                    ])

                    lectureday = SEM_START + (dow - 1) * day
                    lecture = Event()
                    lecture.add('summary', '%s %s' % (item['code'], l['name']))
                    setstartend(lecture,
                                lectureday + ts_hr * hour + ts_min * minute,
                                lectureday + te_hr * hour + te_min * minute)
                    lecture['rrule'] = 'FREQ=YEARLY;BYWEEKNO=%s;BYDAY=%s' % (
                        combstr, WEEKDAY[lec['day'] - 1])
                    lecture['location'] = lec['location']
                    cal.add_component(lecture)

        if item['tutorial_time_table'] != 'null':
            for t in item['tutorial_time_table']:
                for tut in t['sessions']:
                    dow = tut['day']
                    ts = int(tut['starttime'])
                    te = int(tut['endtime'])
                    ts_hr, ts_min = ts / 100, ts % 100
                    te_hr, te_min = te / 100, te % 100

                    combstr = ','.join([
                        str(WEEK2ACTUAL[i - 1] + startweek - 1)
                        for i in tut['occurence'] if i != 1
                    ])  #precautionary check

                    tutday = SEM_START + (dow - 1) * day + (
                        WEEK2ACTUAL[
                            (tut['occurence'][0] if tut['occurence'][0] != 1
                             else tut['occurence'][1]) -
                            1  #another stupid check, tutorials really shouldn't start on 1st week.
                        ] - 1) * week
                    tutorial = Event()
                    tutorial.add('summary',
                                 '%s %s' % (item['code'], t['name']))
                    setstartend(tutorial,
                                tutday + ts_hr * hour + ts_min * minute,
                                tutday + te_hr * hour + te_min * minute)
                    tutorial['rrule'] = 'FREQ=YEARLY;BYWEEKNO=%s;BYDAY=%s' % (
                        combstr, WEEKDAY[tut['day'] - 1])
                    tutorial['location'] = tut['location']
                    cal.add_component(tutorial)

        f = open(os.path.join('ics', ('%s.ics' % item['code'].split()[0])),
                 'wb')
        f.write(cal.as_string())
        f.close()
        return item
Ejemplo n.º 47
0
# generate importance filter string
imp_list = []
for i in xrange(imp, 3):
    imp_list.append("%d" % i)
imp_filter = "(" + ",".join(imp_list) + ")"

q = db.GqlQuery(
    "select * from News_Record_v2 where when > :1 and when < :2 and importance in %s order by when"
    % imp_filter, d_from, d_to)
id = 0
for ev in q:
    if not check_filter(curr_filter, ev.curr):
        continue
    event = Event()
    event['uid'] = "*****@*****.**" % (
        id, time.mktime(ev.when.timetuple()))
    event['summary'] = vText(u"%s, Imp: %s" %
                             (norm_str(ev.title), news.val2imp(ev.importance)))
    event['description'] = vText("Prev: %s\\, Fore: %s" %
                                 (norm_str(ev.pred), norm_str(ev.fore)))
    event['dtstamp'] = ev.when.strftime("%Y%m%dT%H%M%SZ")
    event['dtstart'] = ev.when.strftime("%Y%m%dT%H%M%SZ")
    event['dtend'] = (
        ev.when + datetime.timedelta(minutes=10)).strftime("%Y%m%dT%H%M%SZ")
    event['priority'] = 0
    cal.add_component(event)
    id += 1

print cal.as_string(),
def main():
    city_name = sys.argv[1]
    latitude = sexastr2deci(sys.argv[2])
    longitude = sexastr2deci(sys.argv[3])
    tz = sys.argv[4]

    start_year = int(sys.argv[5])
    year = start_year
    jd = swisseph.julday(year, 1, 1, 0)
    jd_start = jd

    if len(sys.argv) == 7:
        script = sys.argv[6]
    else:
        script = 'deva'  #Default script is devanagari

    swisseph.set_sid_mode(swisseph.SIDM_LAHIRI)  #Force Lahiri Ayanamsha

    sun_month_day = jd - get_last_dhanur_transit(jd, latitude, longitude)

    month_start_after_set = 0

    template_file = open('cal_template_compre.tex')
    template_lines = template_file.readlines()
    for i in range(0, len(template_lines) - 3):
        print template_lines[i][:-1]

    samvatsara_id = (year - 1568) % 60 + 1
    #distance from prabhava
    samvatsara_names = '%s–%s' % (year_names[script][samvatsara_id],
                                  year_names[script][(samvatsara_id % 60) + 1])
    new_yr = mesha_sankranti[script] + '~(' + year_names[script][
        (samvatsara_id % 60) + 1] + '-' + samvatsara[script] + ')'

    print '\\mbox{}'
    print '{\\font\\x="Candara" at 60 pt\\x %d\\\\[0.5cm]}' % year
    print '\\mbox{\\font\\x="Sanskrit 2003:script=deva" at 48 pt\\x %s}\\\\[0.5cm]' % samvatsara_names
    print '{\\font\\x="Candara" at 48 pt\\x \\uppercase{%s}\\\\[0.5cm]}' % city_name
    print '\hrule'

    #INITIALISE VARIABLES
    jd_sunrise = [None] * 368
    jd_sunset = [None] * 368
    jd_moonrise = [None] * 368
    longitude_moon = [None] * 368
    longitude_sun = [None] * 368
    longitude_sun_set = [None] * 368
    sun_month_id = [None] * 368
    sun_month = [None] * 368
    sun_month_rise = [None] * 368
    moon_month = [None] * 368
    month_data = [None] * 368
    tithi_data_string = [None] * 368
    tithi_sunrise = [None] * 368
    nakshatram_data_string = [None] * 368
    nakshatram_sunrise = [None] * 368
    karanam_data_string = [None] * 368
    karanam_sunrise = [None] * 368
    yogam_data_string = [None] * 368
    yogam_sunrise = [None] * 368
    weekday = [None] * 368
    sunrise = [None] * 368
    sunset = [None] * 368
    madhya = [None] * 368
    rahu = [None] * 368
    yama = [None] * 368
    festival_day_list = {}
    festivals = [''] * 368

    weekday_start = swisseph.day_of_week(jd) + 1
    #swisseph has Mon = 0, non-intuitively!

    ##################################################
    #Compute all parameters -- latitude/longitude etc#
    ##################################################

    for d in range(-1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        local_time = pytz.timezone(tz).localize(datetime(y, m, dt, 6, 0, 0))
        #checking @ 6am local - can we do any better?
        tz_off = datetime.utcoffset(local_time).seconds / 3600.0
        #compute offset from UTC

        jd_sunrise[d + 1] = swisseph.rise_trans(
            jd_start=jd + 1,
            body=swisseph.SUN,
            lon=longitude,
            lat=latitude,
            rsmi=swisseph.CALC_RISE | swisseph.BIT_DISC_CENTER)[1][0]
        jd_sunset[d + 1] = swisseph.rise_trans(
            jd_start=jd + 1,
            body=swisseph.SUN,
            lon=longitude,
            lat=latitude,
            rsmi=swisseph.CALC_SET | swisseph.BIT_DISC_CENTER)[1][0]
        jd_moonrise[d + 1] = swisseph.rise_trans(
            jd_start=jd + 1,
            body=swisseph.MOON,
            lon=longitude,
            lat=latitude,
            rsmi=swisseph.CALC_RISE | swisseph.BIT_DISC_CENTER)[1][0]

        longitude_sun[d + 1] = swisseph.calc_ut(
            jd_sunrise[d + 1], swisseph.SUN)[0] - swisseph.get_ayanamsa(
                jd_sunrise[d + 1])
        longitude_moon[d + 1] = swisseph.calc_ut(
            jd_sunrise[d + 1], swisseph.MOON)[0] - swisseph.get_ayanamsa(
                jd_sunrise[d + 1])
        longitude_sun_set[d + 1] = swisseph.calc_ut(
            jd_sunset[d + 1], swisseph.SUN)[0] - swisseph.get_ayanamsa(
                jd_sunset[d + 1])

        sun_month_id[d + 1] = int(1 + math.floor((
            (longitude_sun_set[d + 1]) % 360) / 30.0))
        sun_month[d + 1] = int(1 + math.floor((
            (longitude_sun_set[d + 1]) % 360) / 30.0))

        sun_month_rise[d + 1] = int(1 + math.floor((
            (longitude_sun[d + 1]) % 360) / 30.0))

        if (d <= 0):
            continue

        t_sunrise = (jd_sunrise[d] - jd) * 24.0 + tz_off
        t_sunset = (jd_sunset[d] - jd) * 24.0 + tz_off

        #Solar month calculations
        if month_start_after_set == 1:
            sun_month_day = 0
            month_start_after_set = 0

        if sun_month[d] != sun_month[d + 1]:
            sun_month_day = sun_month_day + 1

            if sun_month[d] != sun_month_rise[d + 1]:
                month_start_after_set = 1
                [_m, sun_month_end_time] = get_angam_data_string(
                    masa_names[script], 30, jd_sunrise[d], jd_sunrise[d + 1],
                    t_sunrise, longitude_moon[d], longitude_sun[d],
                    longitude_moon[d + 1], longitude_sun[d + 1], [0, 1],
                    script)

        elif sun_month_rise[d] != sun_month[d]:
            #mAsa pirappu!
            #sun moves into next rAsi before sunset -- check rules!
            sun_month_day = 1

            [_m, sun_month_end_time] = get_angam_data_string(
                masa_names[script], 30, jd_sunrise[d], jd_sunrise[d + 1],
                t_sunrise, longitude_moon[d], longitude_sun[d],
                longitude_moon[d + 1], longitude_sun[d + 1], [0, 1], script)

        else:
            sun_month_day = sun_month_day + 1
            sun_month_end_time = ''

        month_data[d] = '\\sunmonth{%s}{%d}{%s}' % (masa_names[script][
            sun_month[d]], sun_month_day, sun_month_end_time)

        #KARADAYAN NOMBU -- easy to check here
        if sun_month_end_time != '':  #month ends today
            if (sun_month[d] == 12
                    and sun_month_day == 1) or (sun_month[d] == 11
                                                and sun_month_day != 1):
                festival_day_list[karadayan_nombu[script]] = [d]

        #Sunrise/sunset and related stuff (like rahu, yama)
        [rhs, rms, rss] = deci2sexa(
            t_sunrise)  #rise hour sun, rise minute sun, rise sec sun
        [shs, sms, sss] = deci2sexa(t_sunset)

        length_of_day = t_sunset - t_sunrise
        yamagandam_start = t_sunrise + (1 / 8.0) * (
            yamagandam_octets[weekday] - 1) * length_of_day
        yamagandam_end = yamagandam_start + (1 / 8.0) * length_of_day
        rahukalam_start = t_sunrise + (1 / 8.0) * (rahukalam_octets[weekday] -
                                                   1) * length_of_day
        rahukalam_end = rahukalam_start + (1 / 8.0) * length_of_day
        madhyahnikam_start = t_sunrise + (1 / 5.0) * length_of_day

        sunrise[d] = '%02d:%02d' % (rhs, rms)
        sunset[d] = '%02d:%02d' % (shs, sms)
        madhya[d] = print_time(madhyahnikam_start)
        rahu[d] = '%s--%s' % (print_time(rahukalam_start),
                              print_time(rahukalam_end))
        yama[d] = '%s--%s' % (print_time(yamagandam_start),
                              print_time(yamagandam_end))

        [tithi_sunrise[d], tithi_data_string[d]] = get_angam_data_string(
            tithi_names[script], 12, jd_sunrise[d], jd_sunrise[d + 1],
            t_sunrise, longitude_moon[d], longitude_sun[d],
            longitude_moon[d + 1], longitude_sun[d + 1], [1, -1], script)
        [nakshatram_sunrise[d],
         nakshatram_data_string[d]] = get_angam_data_string(
             nakshatra_names[script], (360.0 / 27.0), jd_sunrise[d],
             jd_sunrise[d + 1], t_sunrise, longitude_moon[d], longitude_sun[d],
             longitude_moon[d + 1], longitude_sun[d + 1], [1, 0], script)
        [karanam_sunrise[d], karanam_data_string[d]] = get_angam_data_string(
            karanam_names[script], 6, jd_sunrise[d], jd_sunrise[d + 1],
            t_sunrise, longitude_moon[d], longitude_sun[d],
            longitude_moon[d + 1], longitude_sun[d + 1], [1, -1], script)
        [yogam_sunrise[d], yogam_data_string[d]] = get_angam_data_string(
            yogam_names[script], (360.0 / 27.0), jd_sunrise[d],
            jd_sunrise[d + 1], t_sunrise, longitude_moon[d], longitude_sun[d],
            longitude_moon[d + 1], longitude_sun[d + 1], [1, 1], script)

    #ASSIGN MOON MONTHS
    last_month_change = 1
    last_moon_month = None
    for d in range(1, 367):
        #Assign moon_month for each day
        if (tithi_sunrise[d] == 1):
            for i in range(last_month_change, d):
                #print '%%#Setting moon_month to sun_month_id, for i=%d:%d to %d' %(last_month_change,d-1,sun_month_id[d])
                if (sun_month_id[d] == last_moon_month):
                    moon_month[i] = sun_month_id[d] % 12 + 0.5
                else:
                    moon_month[i] = sun_month_id[d]
            last_month_change = d
            last_moon_month = sun_month_id[d]
        elif (tithi_sunrise[d] == 2 and tithi_sunrise[d - 1] == 30):
            #prathama tithi was never seen @ sunrise
            for i in range(last_month_change, d):
                #print '%%@Setting moon_month to sun_month_id, for i=%d:%d to %d (last month = %d)' %(last_month_change,d-1,sun_month_id[d],last_moon_month)
                if (sun_month_id[d - 1] == last_moon_month):
                    moon_month[i] = sun_month_id[d - 1] % 12 + 0.5
                else:
                    moon_month[i] = sun_month_id[d - 1]
            last_month_change = d
            last_moon_month = sun_month_id[d - 1]

    for i in range(last_month_change, 367):
        moon_month[i] = sun_month_id[last_month_change - 1] + 1

    #for d in range(1,367):
    #jd = jd_start-1+d
    #[y,m,dt,t] = swisseph.revjul(jd)
    #print '%%#%02d-%02d-%4d: %3d:%s (sunrise tithi=%d) {%s}' % (dt,m,y,d,moon_month[d],tithi_sunrise[d],tithi_data_string[d])

    log_file = open('cal_log_%4d.txt' % year, 'w')
    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        log_data = '%02d-%02d-%4d\t[%3d]\tsun_rashi=%8.3f\ttithi=%8.3f\tsun_month=%2d\tmoon_month=%4.1f\n' % (
            dt, m, y, d, (longitude_sun_set[d] % 360) / 30.0,
            get_angam_float(jd_sunrise[d], 12.0,
                            [1, -1]), sun_month[d], moon_month[d])
        log_file.write(log_data)

    #PRINT CALENDAR

    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        ##################
        #Festival details#
        ##################

        ###--- MONTHLY VRATAMS ---###

        #EKADASHI Vratam
        if tithi_sunrise[d] == 11 or tithi_sunrise[
                d] == 12:  #One of two consecutive tithis must appear @ sunrise!
            #check for shukla ekadashi[script]
            if (tithi_sunrise[d] == 11 and tithi_sunrise[d + 1] == 11):
                festivals[d + 1] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='shukla', month=moon_month[d],
                    script=script)  #moon_month[d] or [d+1]?
                if moon_month[d + 1] == 4:
                    festivals[d + 1] += '\\\\' + chaturmasya_start[script]
                if moon_month[d + 1] == 8:
                    festivals[d + 1] += '\\\\' + chaturmasya_end[script]
            elif (tithi_sunrise[d] == 11 and tithi_sunrise[d + 1] != 11):
                #Check dashami end time to decide for whether this is sarva[script]/smartha[script]
                tithi_arunodayam = get_tithi(
                    jd_sunrise[d] - (1 / 15.0) *
                    (jd_sunrise[d] - jd_sunrise[d - 1])
                )  #Two muhurtams is 1/15 of day-length
                if tithi_arunodayam == 10:
                    festivals[d] = smartha[script] + '~' + get_ekadashi_name(
                        paksha='shukla', month=moon_month[d], script=script)
                    festivals[d +
                              1] = vaishnava[script] + '~' + get_ekadashi_name(
                                  paksha='shukla',
                                  month=moon_month[d],
                                  script=script)
                    if moon_month[d] == 4:
                        festivals[d] += '\\\\' + chaturmasya_start[script]
                    if moon_month[d] == 8:
                        festivals[d] += '\\\\' + chaturmasya_end[script]
                else:
                    festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                        paksha='shukla', month=moon_month[d], script=script)
                    if moon_month[d] == 4:
                        festivals[d] += '\\\\' + chaturmasya_start[script]
                    if moon_month[d] == 8:
                        festivals[d] += '\\\\' + chaturmasya_end[script]
            elif (tithi_sunrise[d - 1] != 11 and tithi_sunrise[d] == 12):
                festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='shukla', month=moon_month[d], script=script)
                if moon_month[d] == 4:
                    festivals[d] += '\\\\' + chaturmasya_start[script]
                if moon_month[d] == 8:
                    festivals[d] += '\\\\' + chaturmasya_end[script]

        if tithi_sunrise[d] == 26 or tithi_sunrise[
                d] == 27:  #One of two consecutive tithis must appear @ sunrise!
            #check for krishna ekadashi[script]
            if (tithi_sunrise[d] == 26 and tithi_sunrise[d + 1] == 26):
                festivals[d + 1] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='krishna', month=moon_month[d],
                    script=script)  #moon_month[d] or [d+1]?
            elif (tithi_sunrise[d] == 26 and tithi_sunrise[d + 1] != 26):
                #Check dashami end time to decide for whether this is sarva[script]/smartha[script]
                tithi_arunodayam = get_tithi(
                    jd_sunrise[d] - (1 / 15.0) *
                    (jd_sunrise[d] - jd_sunrise[d - 1])
                )  #Two muhurtams is 1/15 of day-length
                if tithi_arunodayam == 25:
                    festivals[d] = smartha[script] + '~' + get_ekadashi_name(
                        paksha='krishna', month=moon_month[d], script=script)
                    festivals[d +
                              1] = vaishnava[script] + '~' + get_ekadashi_name(
                                  paksha='krishna',
                                  month=moon_month[d],
                                  script=script)
                else:
                    festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                        paksha='krishna', month=moon_month[d], script=script)
            elif (tithi_sunrise[d - 1] != 26 and tithi_sunrise[d] == 27):
                festivals[d] = sarva[script] + '~' + get_ekadashi_name(
                    paksha='krishna', month=moon_month[d], script=script)

        #PRADOSHA Vratam
        if tithi_sunrise[d] == 12 or tithi_sunrise[d] == 13:
            ldiff_set = (swisseph.calc_ut(jd_sunset[d], swisseph.MOON)[0] -
                         swisseph.calc_ut(jd_sunset[d], swisseph.SUN)[0]) % 360
            ldiff_set_tmrw = (
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.SUN)[0]) % 360
            tithi_sunset = int(1 + math.floor(ldiff_set / 12.0))
            tithi_sunset_tmrw = int(1 + math.floor(ldiff_set_tmrw / 12.0))
            if tithi_sunset <= 13 and tithi_sunset_tmrw != 13:
                festivals[d] = pradosham[script]
            elif tithi_sunset_tmrw == 13:
                festivals[d + 1] = pradosham[script]

        if tithi_sunrise[d] == 27 or tithi_sunrise[d] == 28:
            ldiff_set = (swisseph.calc_ut(jd_sunset[d], swisseph.MOON)[0] -
                         swisseph.calc_ut(jd_sunset[d], swisseph.SUN)[0]) % 360
            ldiff_set_tmrw = (
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_sunset[d + 1], swisseph.SUN)[0]) % 360
            tithi_sunset = int(1 + math.floor(ldiff_set / 12.0))
            tithi_sunset_tmrw = int(1 + math.floor(ldiff_set_tmrw / 12.0))
            if tithi_sunset <= 28 and tithi_sunset_tmrw != 28:
                festivals[d] = pradosham[script]
            elif tithi_sunset_tmrw == 28:
                festivals[d + 1] = pradosham[script]

        #SANKATAHARA chaturthi[script]
        if tithi_sunrise[d] == 18 or tithi_sunrise[d] == 19:
            ldiff_moonrise_yest = (
                swisseph.calc_ut(jd_moonrise[d - 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_moonrise[d - 1], swisseph.SUN)[0]) % 360
            ldiff_moonrise = (
                swisseph.calc_ut(jd_moonrise[d], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_moonrise[d], swisseph.SUN)[0]) % 360
            ldiff_moonrise_tmrw = (
                swisseph.calc_ut(jd_moonrise[d + 1], swisseph.MOON)[0] -
                swisseph.calc_ut(jd_moonrise[d + 1], swisseph.SUN)[0]) % 360
            tithi_moonrise_yest = int(1 +
                                      math.floor(ldiff_moonrise_yest / 12.0))
            tithi_moonrise = int(1 + math.floor(ldiff_moonrise / 12.0))
            tithi_moonrise_tmrw = int(1 +
                                      math.floor(ldiff_moonrise_tmrw / 12.0))

            if tithi_moonrise == 19:
                if tithi_moonrise_yest != 19:  #otherwise yesterday would have already been assigned
                    festivals[d] = chaturthi[script]
                    if moon_month[d] == 5:  #shravana krishna chaturthi[script]
                        festivals[d] = maha[script] + festivals[d]
            elif tithi_moonrise_tmrw == 19:
                festivals[d + 1] = chaturthi[script]
                if moon_month[
                        d] == 5:  #moon_month[d] and[d+1] are same, so checking [d] is enough
                    festivals[d + 1] = maha[script] + festivals[d + 1]

        #SHASHTHI Vratam
        if tithi_sunrise[d] == 5 or tithi_sunrise[d] == 6:
            if tithi_sunrise[d] == 6 or (tithi_sunrise[d] == 5
                                         and tithi_sunrise[d + 1] == 7):
                if tithi_sunrise[
                        d -
                        1] != 6:  #otherwise yesterday would have already been assigned
                    festivals[d] = shashthi[script]
                    if moon_month[d] == 8:  #kArtika krishna shashthi[script]
                        festivals[d] = skanda[script] + festivals[d]
            elif tithi_sunrise[d + 1] == 6:
                festivals[d + 1] = shashthi[script]
                if moon_month[
                        d] == 8:  #moon_month[d] and[d+1] are same, so checking [d] is enough
                    festivals[d + 1] = skanda[script] + festivals[d + 1]

        ###--- OTHER (MAJOR) FESTIVALS ---###
        #type of month | month number | type of angam (tithi|nakshatram) | angam number | min_t cut off for considering prev day (without sunrise_angam) as festival date
        purvaviddha_rules = {
            akshaya_tritiya[script]: ['moon_month', 2, 'tithi', 3, 0],
            chitra_purnima[script]: ['sun_month', 1, 'tithi', 15, 0],
            durgashtami[script]: ['moon_month', 7, 'tithi', 8, 0],
            mahanavami[script]: ['moon_month', 7, 'tithi', 9, 0],
            vijayadashami[script]: ['moon_month', 7, 'tithi', 10, 0],
            dipavali[script]: ['moon_month', 7, 'tithi', 29, 0],
            shankara_jayanti[script]: ['moon_month', 2, 'tithi', 5, 0],
            yajur_upakarma[script]: ['moon_month', 5, 'tithi', 15, 0],
            rg_upakarma[script]: ['moon_month', 5, 'nakshatram', 22, 0],
            sama_upakarma[script]: ['sun_month', 5, 'nakshatram', 13, 0],
            rishi_panchami[script]: ['moon_month', 6, 'tithi', 5, 0],
            ananta_chaturdashi[script]: ['moon_month', 6, 'tithi', 14, 0],
            mahalaya_paksham[script]: ['moon_month', 6, 'tithi', 16, 0],
            hanumat_jayanti[script]: ['sun_month', 9, 'tithi', 30, 0],
            ardra_darshanam[script]: ['sun_month', 9, 'nakshatram', 6, 0],
            ratha_saptami[script]: ['sun_month', 10, 'tithi', 7, 0],
            goda_jayanti[script]: ['sun_month', 4, 'nakshatram', 11, 0],
            adi_krittika[script]: ['sun_month', 4, 'nakshatram', 3, 0],
            phalguni_uttaram[script]: ['sun_month', 12, 'nakshatram', 12, 4],
            mahalaya_amavasya[script]: ['moon_month', 6, 'tithi', 30, 0],
            uma_maheshvara_vratam[script]: ['moon_month', 6, 'tithi', 15, 0]
        }

        for x in iter(purvaviddha_rules.keys()):
            rule = purvaviddha_rules[x]
            if rule[0] == 'moon_month':
                if moon_month[d] == rule[1]:
                    if rule[2] == 'tithi':
                        fday = get_festival_day_purvaviddha(
                            rule[3], tithi_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_tithi, rule[4])
                    elif rule[2] == 'nakshatram':
                        fday = get_festival_day_purvaviddha(
                            rule[3], nakshatram_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_nakshatram, rule[4])
                    if fday is not None:
                        if festival_day_list.has_key(x):
                            if festival_day_list[x][0] != fday:
                                #Second occurrence of a festival within a Gregorian calendar year
                                festival_day_list[x] = [
                                    festival_day_list[x][0], fday
                                ]
                        else:
                            festival_day_list[x] = [fday]
            elif rule[0] == 'sun_month':
                if sun_month[d] == rule[1]:
                    if rule[2] == 'tithi':
                        fday = get_festival_day_purvaviddha(
                            rule[3], tithi_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_tithi, rule[4])
                    elif rule[2] == 'nakshatram':
                        fday = get_festival_day_purvaviddha(
                            rule[3], nakshatram_sunrise, d, jd_sunrise[d],
                            jd_sunrise[d + 1], get_nakshatram, rule[4])
                    if fday is not None:
                        if festival_day_list.has_key(x):
                            if festival_day_list[x][0] != fday:
                                #Second occurrence of a festival within a Gregorian calendar year
                                festival_day_list[x] = [
                                    festival_day_list[x][0], fday
                                ]
                        else:
                            festival_day_list[x] = [fday]
            else:
                print 'Error; unknown string in rule: %s' % (rule[0])
                return

        #NAVARATRI START
        if moon_month[d] == 7 and moon_month[d - 1] == 6:
            festival_day_list[navaratri_start[script]] = [d]

        #PONGAL/AYANAM
        if sun_month[d] == 10 and sun_month[d - 1] == 9:
            festival_day_list[uttarayanam[script]] = [d]

        if sun_month[d] == 4 and sun_month[d - 1] == 3:
            festival_day_list[dakshinayanam[script]] = [d]

        if sun_month[d] == 1 and sun_month[d - 1] == 12:
            festival_day_list[new_yr] = [d]

        if moon_month[d] == 1 and moon_month[d - 1] != 1:
            festival_day_list[yugadi[script]] = [d]

        #SHRIRAMANAVAMI
        if moon_month[d] == 1:
            if tithi_sunrise[d] == 8 or tithi_sunrise[d] == 9:
                t_11 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (2.0 / 5.0))  #madhyahna1 start
                t_12 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (3.0 / 5.0))  #madhyahna1 end
                t_21 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (2.0 / 5.0))  #madhyahna2 start
                t_22 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (3.0 / 5.0))  #madhyahna2 end
                if t_11 == 9 or t_12 == 9:
                    if t_21 == 9 or t_22 == 9:
                        festival_day_list[ramanavami[script]] = [d + 1]
                    else:
                        festival_day_list[ramanavami[script]] = [d]

        #JANMASHTAMI
        if moon_month[d] == 5:
            if tithi_sunrise[d] == 22 or tithi_sunrise[d] == 23:
                t_11 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (7.0 / 15.0))  #nishita1 start
                t_12 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (8.0 / 15.0))  #nishita1 end
                #t_11 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(2.0/5.0))#madhyaratri1 start
                #t_12 = get_tithi(jd_sunset[d]+(jd_sunrise[d+1]-jd_sunset[d])*(3.0/5.0))#madhyaratri1 end
                t_21 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (7.0 / 15.0))  #nishita2 start
                t_22 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (8.0 / 15.0))  #nishita2 end
                #t_21 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(2.0/5.0))#madhyaratri2 start
                #t_22 = get_tithi(jd_sunset[d+1]+(jd_sunrise[d+2]-jd_sunset[d+1])*(3.0/5.0))#madhyaratri2 end
                if t_11 == 23 or t_12 == 23:
                    if t_21 == 23 or t_22 == 23:
                        festival_day_list[janmashtami[script]] = [d + 1]
                    else:
                        festival_day_list[janmashtami[script]] = [d]

        #SHIVARATRI
        if moon_month[d] == 11:
            if tithi_sunrise[d] == 28 or tithi_sunrise[d] == 29:
                t_11 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (7.0 / 15.0))  #nishita1 start
                t_12 = get_tithi(jd_sunset[d] +
                                 (jd_sunrise[d + 1] - jd_sunset[d]) *
                                 (8.0 / 15.0))  #nishita1 end
                t_21 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (7.0 / 15.0))  #nishita2 start
                t_22 = get_tithi(jd_sunset[d + 1] +
                                 (jd_sunrise[d + 2] - jd_sunset[d + 1]) *
                                 (8.0 / 15.0))  #nishita2 end
                if t_11 == 29 or t_12 == 29:
                    if t_21 == 29 or t_22 == 29:
                        festival_day_list[shivaratri[script]] = [d + 1]
                    else:
                        festival_day_list[shivaratri[script]] = [d]

        #VINAYAKA CHATURTHI
        if moon_month[d] == 6:
            if tithi_sunrise[d] == 3 or tithi_sunrise[d] == 4:
                t_11 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (2.0 / 5.0))  #madhyahna1 start
                t_12 = get_tithi(jd_sunrise[d] +
                                 (jd_sunset[d] - jd_sunrise[d]) *
                                 (3.0 / 5.0))  #madhyahna1 end
                t_21 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (2.0 / 5.0))  #madhyahna2 start
                t_22 = get_tithi(jd_sunrise[d + 1] +
                                 (jd_sunset[d + 1] - jd_sunrise[d + 1]) *
                                 (3.0 / 5.0))  #madhyahna2 end
                if t_11 == 4 or t_12 == 4:
                    if t_21 == 4 or t_22 == 4:
                        festival_day_list[vchaturthi[script]] = [d + 1]
                    else:
                        festival_day_list[vchaturthi[script]] = [d]

    #Add saved festivals
    festival_day_list[gayatri_japam[script]] = [
        festival_day_list[yajur_upakarma[script]][0] + 1
    ]
    festival_day_list[varalakshmi_vratam[script]] = [
        festival_day_list[yajur_upakarma[script]][0] -
        ((weekday_start - 1 + festival_day_list[yajur_upakarma[script]][0] - 5)
         % 7)
    ]
    #KARADAYAN_NOMBU
    for x in iter(festival_day_list.keys()):
        for j in range(0, len(festival_day_list[x])):
            if festivals[festival_day_list[x][j]] != '':
                festivals[festival_day_list[x][j]] += '\\\\'
            festivals[festival_day_list[x][j]] += x

    ###--- ECLIPSES ---###
    ###--- LUNAR ECLIPSES ---###
    swisseph.set_topo(lon=longitude, lat=latitude, alt=0.0)  #Set location
    jd = jd_start
    while 1:
        next_ecl_lun = swisseph.lun_eclipse_when(jd)
        jd = next_ecl_lun[1][0] + (tz_off / 24.0)
        jd_ecl_lun_start = next_ecl_lun[1][2] + (tz_off / 24.0)
        jd_ecl_lun_end = next_ecl_lun[1][3] + (tz_off / 24.0)
        ecl_y = swisseph.revjul(
            jd - 1
        )[0]  # -1 is to not miss an eclipse that occurs after sunset on 31-Dec!
        if ecl_y != start_year:
            break
        else:
            ecl_lun_start = swisseph.revjul(jd_ecl_lun_start)[3]
            ecl_lun_end = swisseph.revjul(jd_ecl_lun_end)[3]
            if (jd_ecl_lun_start -
                (tz_off / 24.0)) == 0.0 or (jd_ecl_lun_end -
                                            (tz_off / 24.0)) == 0.0:
                jd = jd + 20  #Move towards the next eclipse... at least the next full moon (>=25 days away)
                continue
            fday = int(math.floor(jd_ecl_lun_start) - math.floor(jd_start) + 1)
            #print '%%',jd,fday,jd_sunrise[fday],jd_sunrise[fday-1]
            if (jd < (jd_sunrise[fday] + tz_off / 24.0)):
                fday -= 1
            if ecl_lun_start < swisseph.revjul(jd_sunrise[fday + 1] +
                                               tz_off / 24.0)[3]:
                ecl_lun_start += 24
            #print '%%',jd,fday,jd_sunrise[fday],jd_sunrise[fday-1],ecl_lun_start, ecl_lun_end
            jd_moonrise_ecl_day = swisseph.rise_trans(
                jd_start=jd_sunrise[fday],
                body=swisseph.MOON,
                lon=longitude,
                lat=latitude,
                rsmi=swisseph.CALC_RISE
                | swisseph.BIT_DISC_CENTER)[1][0] + (tz_off / 24.0)
            jd_moonset_ecl_day = swisseph.rise_trans(
                jd_start=jd_moonrise_ecl_day,
                body=swisseph.MOON,
                lon=longitude,
                lat=latitude,
                rsmi=swisseph.CALC_SET
                | swisseph.BIT_DISC_CENTER)[1][0] + (tz_off / 24.0)
            #if jd_ecl_lun_start<(jd_sunrise[fday]+(tz_off/24.0)):
            if ecl_lun_end < ecl_lun_start:
                ecl_lun_end += 24
            #print '%%', (jd_ecl_lun_start), (jd_ecl_lun_end), (jd_moonrise_ecl_day), (jd_moonset_ecl_day)
            #print '%%', swisseph.revjul(jd_ecl_lun_start), swisseph.revjul(jd_ecl_lun_end), swisseph.revjul(jd_moonrise_ecl_day), swisseph.revjul(jd_moonset_ecl_day)
            if jd_ecl_lun_end < jd_moonrise_ecl_day or jd_ecl_lun_start > jd_moonset_ecl_day:
                jd = jd + 20  #Move towards the next eclipse... at least the next full moon (>=25 days away)
                continue
            lun_ecl_str = chandra_grahanam[script] + '~\\textsf{' + print_time2(
                ecl_lun_start) + '}{\\RIGHTarrow}\\textsf{' + print_time2(
                    ecl_lun_end) + '}'
            if festivals[fday] != '':
                festivals[fday] += '\\\\'
            festivals[fday] += lun_ecl_str
        jd = jd + 20

    ###--- SOLAR ECLIPSES ---###
    swisseph.set_topo(lon=longitude, lat=latitude, alt=0.0)  #Set location
    jd = jd_start
    while 1:
        next_ecl_sol = swisseph.sol_eclipse_when_loc(julday=jd,
                                                     lon=longitude,
                                                     lat=latitude)
        jd = next_ecl_sol[1][0] + (tz_off / 24.0)
        jd_ecl_sol_start = next_ecl_sol[1][1] + (tz_off / 24.0)
        jd_ecl_sol_end = next_ecl_sol[1][4] + (tz_off / 24.0)
        ecl_y = swisseph.revjul(
            jd - 1
        )[0]  # -1 is to not miss an eclipse that occurs after sunset on 31-Dec!
        if ecl_y != start_year:
            break
        else:
            #print '%%', fday, (jd_ecl_sol_start), (jd_ecl_sol_end), (jd_sunrise[fday])
            #print '%%', swisseph.revjul(jd_ecl_sol_start), swisseph.revjul(jd_ecl_sol_end), swisseph.revjul(jd_sunrise[fday])
            fday = int(math.floor(jd) - math.floor(jd_start) + 1)
            if (jd < (jd_sunrise[fday] + tz_off / 24.0)):
                fday -= 1
            #print '%%', fday, (jd_ecl_sol_start), (jd_ecl_sol_end), (jd_sunrise[fday])
            #print '%%', swisseph.revjul(jd_ecl_sol_start), swisseph.revjul(jd_ecl_sol_end), swisseph.revjul(jd_sunrise[fday])
            ecl_sol_start = swisseph.revjul(jd_ecl_sol_start)[3]
            ecl_sol_end = swisseph.revjul(jd_ecl_sol_end)[3]
            if (jd_ecl_sol_start - (tz_off / 24.0)) == 0.0 or (
                    jd_ecl_sol_end - (tz_off / 24.0)
            ) == 0.0:  # or jd_ecl_end<jd_sunrise[fday] or jd_ecl_start>jd_sunset[fday]:
                jd = jd + 20  #Move towards the next eclipse... at least the next new moon (>=25 days away)
                continue
            if ecl_sol_end < ecl_sol_start:
                ecl_sol_end += 24
            sol_ecl_str = surya_grahanam[script] + '~\\textsf{' + print_time2(
                ecl_sol_start) + '}{\\RIGHTarrow}\\textsf{' + print_time2(
                    ecl_sol_end) + '}'
            if festivals[fday] != '':
                festivals[fday] += '\\\\'
            festivals[fday] += sol_ecl_str
        jd = jd + 20
    ###--- FESTIVAL ADDITIONS COMPLETE ---###

    ###--- PRINT LIST OF FESTIVALS (Page 2) ---###
    if script == 'en':
        cal = Calendar()

    print '\\newpage'
    print '\\centerline {\\LARGE {{%s}}}\\mbox{}\\\\[2cm]' % list_of_festivals[
        script]
    print '\\begin{center}'
    print '\\begin{minipage}[t]{0.3\\linewidth}'
    print '\\begin{center}'
    print '\\begin{tabular}{>{\\sffamily}r>{\\sffamily}r>{\\sffamily}cp{6cm}}'

    mlast = 1
    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        if festivals[d] != '':
            if m != mlast:
                mlast = m
                #print '\\hline\\\\'
                print '\\\\'
                if m == 5 or m == 9:
                    print '\\end{tabular}'
                    print '\\end{center}'
                    print '\\end{minipage}\hspace{1cm}%'
                    print '\\begin{minipage}[t]{0.3\\linewidth}'
                    print '\\begin{center}'
                    print '\\begin{tabular}{>{\\sffamily}r>{\\sffamily}l>{\\sffamily}cp{6cm}}'

            print '%s & %s & %s & {\\raggedright %s} \\\\' % (
                MON[m], dt, WDAY[weekday], festivals[d])

            if script == 'en':
                event = Event()
                event.add('summary', festivals[d])
                event.add('dtstart', datetime(y, m, dt))
                event.add('dtend', datetime(y, m, dt))
                cal.add_component(event)

        if m == 12 and dt == 31:
            break

    print '\\end{tabular}'
    print '\\end{center}'
    print '\\end{minipage}'
    print '\\end{center}'
    print '\\clearpage'

    if script == 'en':
        cal_fname = '%s-%4d.ics' % (city_name, start_year)
        cal_file = open(cal_fname, 'w')
        cal_file.write(cal.as_string())
        cal_file.close()

    #Layout calendar in LATeX format
    #We use a separate loop here, because of festivals like varalakshmi
    #vratam, for which we backtrack to the previous friday from yajur
    #upakarma and change the list of festivals!

    for d in range(1, 367):
        jd = jd_start - 1 + d
        [y, m, dt, t] = swisseph.revjul(jd)
        weekday = (weekday_start - 1 + d) % 7

        if dt == 1:
            if m > 1:
                if weekday != 0:  #Space till Sunday
                    for i in range(weekday, 6):
                        print "{}  &"
                    print "\\\\ \hline"
                print '\end{tabular}'
                print '\n\n'

            #Begin tabular
            print '\\begin{tabular}{|c|c|c|c|c|c|c|}'
            print '\multicolumn{7}{c}{\Large \\bfseries \sffamily %s %s}\\\\[3mm]' % (
                month[m], y)
            print '\hline'
            print '\\textbf{\\textsf{SUN}} & \\textbf{\\textsf{MON}} & \\textbf{\\textsf{TUE}} & \\textbf{\\textsf{WED}} & \\textbf{\\textsf{THU}} & \\textbf{\\textsf{FRI}} & \\textbf{\\textsf{SAT}} \\\\ \hline'
            #print '\\textbf{भानु} & \\textbf{इन्दु} & \\textbf{भौम} & \\textbf{बुध} & \\textbf{गुरु} & \\textbf{भृगु} & \\textbf{स्थिर} \\\\ \hline'

            #Blanks for previous weekdays
            for i in range(0, weekday):
                print "{}  &"

        print '\caldata{\\textcolor{%s}{%s}}{%s{%s}}{\\sundata{%s}{%s}{%s}}{\\tnyk{%s}{%s}{%s}{%s}}{\\rahuyama{%s}{%s}}{%s} ' % (
            daycol[weekday], dt, month_data[d],
            get_chandra_masa(moon_month[d], chandra_masa_names, script),
            sunrise[d], sunset[d], madhya[d], tithi_data_string[d],
            nakshatram_data_string[d], yogam_data_string[d],
            karanam_data_string[d], rahu[d], yama[d], festivals[d])

        if weekday == 6:
            print "\\\\ \hline"
        else:
            print "&"

        if m == 12 and dt == 31:
            break

        # For debugging specific dates
        #if m==4 and dt==10:
        #  break

    for i in range(weekday + 1, 6):
        print "{}  &"
    if weekday != 6:
        print "\\\\ \hline"
    print '\end{tabular}'
    print '\n\n'

    print template_lines[-2][:-1]
    print template_lines[-1][:-1]
def main():
    """
    Process calendar data present in a feed to build iCalendar events.
    """
    # Grab the feed for processing
    feed_url = len(sys.argv) > 1 and sys.argv[1] or FEED_URL
    ics_fn   = len(sys.argv) > 2 and sys.argv[2] or ICS_FN

    # Get the feed, create a new calendar and an hCalendar parser.
    feed  = feedparser.parse(feed_url)
    cal   = Calendar()
    hp    = HCalendarParser()
    types = TypesFactory()

    # Scan all the feed entries for calendar events.
    for entry in feed.entries:
        
        # First, check for any hCalendar events in the feed summary
        # content.
        if 'summary' in entry:
            # Attempt to parse the entry summary for hCalendar events.
            events = hp.parse(entry['summary'])
            if events:
                # Add all the events, then continue on to next entry.
                for e in events: cal.add_component(e)
                continue
                  
        # Here's an attempt to map feedparser entry metadata
        # to event properties.
        entry_to_event = [
           ( 'link',         'url' ),
           ( 'title',        'summary' ),
           ( 'summary',      'description' ),
           ( 'ev_startdate', 'dtstart' ),
           ( 'ev_enddate',   'dtend' ),
           ( 'ev_location',  'location' ),
           ( 'ev_organizer', 'organizer' ),
           ( 'ev_type',      'type' ),
        ]
        
        # If no events found in entry content, try constructing one from
        # feed metadata values.
        event = Event()
        for entry_key, event_key in entry_to_event:
            
            # Check to see this metadata key is in the entry.
            if entry_key in entry:
                entry_val = entry[entry_key]

                # HACK: Get rid of date and time field separators to
                # better match iCalendar's time format.
                if event_key.startswith('dt'):
                    entry_val = entry_val.replace('-','').replace(':','')
            
                # Convert the entry metadata value to a event date type
                # and add it to the event.
                val = types.from_ical(event_key, entry_val.encode('UTF-8'))
                event.add(event_key, val)

        # Add the event to the calendar after building it.
        cal.add_component(event)

    # Write the iCalendar file out to disk.
    open(ics_fn, "w").write(cal.as_string())
Ejemplo n.º 50
0
                               0,
                               tzinfo=UTC)
        # iCalendar events must be defined by a time slot with a start and a stop date/time.
        # There is no such equivalent in SVN: a commit has just a date.
        # I choose to use the commit date as the end of the iCal event. The start of the event will be set as the commit date minus 5 minutes.
        event_start = py_datetime - timedelta(minutes=TIME_SLOT)

        # Create a new calendar event
        event = Event()
        event.add('summary', 'SVN REV %s' % revision)
        event.add('description', '%s:\n\n%s' % (author, msg))
        event.add('dtstart', event_start)
        event.add('dtend', py_datetime)
        event.add('dtstamp', event_start)
        event['uid'] = '*****@*****.**' % (
            revision, py_datetime, author, random.random())
        event.add('priority', 5)
        cal.add_component(event)
        commit_count += 1

    # Write the iCal file
    f = open(ical_file, "w")
    f.write(cal.as_string())
    f.close()

    # Clean-up and exit
    remove(tmp_log_file)
    print " INFO - Calendar created as '%s' with %s commits." % (ical_file,
                                                                 commit_count)
    sys.exit(0)
    def get(self):
        self.response.headers['Content-Type'] = 'text/calendar; charset=utf-8'

        show_all = "-all" if self.request.get("all") else ""
        calendar = memcache.get("enzian-calendar" + show_all)
        if calendar:
            self.response.out.write(calendar)
            return

        cal = Calendar()
        cal.add('version', '2.0')
        cal.add('prodid', '-//Enzian Specials by Chad//NONSCML//EN')
        cal.add('X-WR-CALID', 'dc7c97b1-951d-404f-ab20-3abcf10ad038')
        cal.add('X-WR-CALNAME', 'Enzian specials')
        cal.add(
            'X-WR-CALDESC',
            "Enzian makes calendars only for eyeballs.  Chad ( https://chad.org/ ) makes computers understand them."
        )
        cal.add('X-WR-TIMEZONE', 'US/Eastern')

        seen = set()
        for fortnights_in_advance in range(4):  # no "month" math in timedelta.
            month = datetime.utcnow().date() + timedelta(days=14 *
                                                         fortnights_in_advance)
            if month.strftime("%Y-%m") in seen:
                continue
            seen.add(month.strftime("%Y-%m"))

            req = urllib2.Request("http://enzian.org/calendar/" +
                                  month.strftime("%Y-%m"),
                                  None,
                                  headers={'User-Agent': 'Mozilla/5.0'})
            page = urllib2.urlopen(req).read()
            soup = BeautifulSoup(page,
                                 convertEntities=BeautifulSoup.HTML_ENTITIES)

            for item in soup.fetch("div", attrs={"data-tribejson": True}):
                doc = json.loads(item["data-tribejson"])
                tags = set(doc["categoryClasses"].split())

                if u'cat_special-program' not in tags:
                    continue

                if u'tribe-events-category-film-slam' in tags:
                    continue

                event = Event()
                if u'cat_popcorn-flicks-in-the-park' in tags:
                    event.add('summary', "park movie: " + doc["title"])
                else:
                    event.add('summary', "Enzian: " + doc["title"])

                event.add(
                    'description',
                    re.sub(u"….*", u"…", doc["excerpt"]).replace("<p>", ""))
                event.add(
                    'dtstamp',
                    datetime.now())  # todo: make this the modtime of page

                start = qualified_date(doc["startTime"], month.year)
                end = qualified_date(doc["endTime"], month.year)

                event.add('dtstart', start)
                event.add('dtend', end)
                event["uid"] = doc["eventId"]

                cal.add_component(event)

        self.response.out.write(cal.as_string())
Ejemplo n.º 52
0
    event.add('location', ev['location'].replace(",","\,"))

    startday = ev['from'].rpartition(" ")[0]
    startdt = datetime.datetime.strptime(ev['from'], "%b %d, %Y %I:%M%p")
    event.add('dtstart;VALUE=DATE-TIME', vDatetime(startdt).ical())
    
    #use different parsing strings depending on if no date
    enddt = datetime.datetime.strptime(ev['to'] if " " in ev['to'] else " ".join([startday,ev['to']]), "%b %d, %Y %I:%M%p")
    event.add('dtend;VALUE=DATE-TIME', vDatetime(enddt).ical())
    
    event.add('dtstamp;VALUE=DATE-TIME', vDatetime(startdt).ical())
    event.add('uid', str(ev['id'])+"/@uoit-guidebook.com")
    event.add('class', 'PUBLIC')

    cal.add_component(event)
print cal.as_string()import scraperwiki
from icalendar import Calendar, Event, UTC, vDatetime
import datetime
from pytz import timezone

sourcescraper = 'uoit_student_center_calendar'
scraperwiki.sqlite.attach(sourcescraper)

data = scraperwiki.sqlite.select("* from uoit_student_center_calendar.swdata")

cal = Calendar()
cal.add('version', '2.0')
cal.add('prodid', '-//Google Inc//Google Calendar 70.9054//EN')
cal.add('calscale', 'GREGORIAN')
cal.add('method', 'PUBLISH')
cal.add('X-WR-CALNAME', 'UOIT Student Center Calendar')
Ejemplo n.º 53
0
    summary = "%s's Birthday" % name
    d = data['random']['anniversary']
    now = date(date.today().year, d.month, d.day)
    if now > date.today():
        d = date(now.year, d.month, d.day)
    else:
        d = date(now.year + 1, d.month, d.day)
    event.add('summary', summary)
    event.add('dtstart', d)
    event.add('dtend', d)
    event.add('dtstamp', datetime.now(UTC))
    event['uid'] = "buttle/" + ''.join(
        c for c in summary if c in string.ascii_letters + string.digits).lower(
        ) + "-" + data['random']['anniversary'].isoformat()
    return event


calendar = Calendar()
calendar.add('version', '2.0')
calendar.add('prodid', '-//buttle//ertius.org//')

with open(options.input) as f:
    for line in f:
        data = parse_line(line)
        if data and 'anniversary' in data['random']:
            event = build_vcal_item(data)
            calendar.add_component(event)

with open(options.output, 'w') as output:
    output.write(calendar.as_string()[:-2])
Ejemplo n.º 54
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/calendar'

        calendar = memcache.get("ksc-calendar")
        if calendar:
            self.response.out.write(calendar)
            return

        cal = Calendar()
        cal.add('version', '2.0')
        cal.add('prodid',
                '-//Kennedy Space Center launches by Chad//NONSCML//EN')
        cal.add('X-WR-CALID', '8293bcab-1b27-44dd-8a3c-2bb045888629')
        cal.add('X-WR-CALNAME', 'KSC launches by Chad')
        cal.add(
            'X-WR-CALDESC',
            "NASA publishes a web page of scheduled launches, but an iCalendar/RFC5545 feed would be so much better and useful.  So, ( https://chad.org/ ) Chad made one.  Enjoy!"
        )
        cal.add('X-WR-TIMEZONE', 'US/Eastern')

        launch_calendar_id = 6089
        two_months_ago = datetime.utcnow() + timedelta(days=-60)
        one_year_from_now = datetime.utcnow() + timedelta(days=365)

        index_json = urllib2.urlopen(
            "https://www.nasa.gov/api/1/query/calendar.json?timeRange={0}--{1}&calendars={2}"
            .format(two_months_ago.strftime("%Y%m%d0000"),
                    one_year_from_now.strftime("%Y%m%d0000"),
                    launch_calendar_id))
        index = json.load(index_json)

        for index_event in index["calendarEvents"]:
            assert index_event["type"] == "calendar_event"
            ev_url = "https://www.nasa.gov/api/1/query/node/{0}.json?{1}".format(
                index_event["nid"], index_event["urlQuery"])
            event_json = urllib2.urlopen(ev_url)
            event_info = json.load(event_json)

            if "eventDate" in event_info["calendarEvent"]:
                for i, event_occurance in enumerate(
                        event_info["calendarEvent"]["eventDate"]):
                    event = Event()

                    event.add(
                        'uid',
                        event_info["calendarEvent"]["uuid"] + "_" + str(i))
                    event.add('summary', event_info["calendarEvent"]["title"])
                    event.add('description',
                              event_info["calendarEvent"]["description"])
                    event.add(
                        'dtstamp',
                        datetime.fromtimestamp(
                            int(event_info["calendarEvent"]["changed"])))

                    date_start = datetime.strptime(
                        event_occurance["value"][:-5], "%Y-%m-%dT%H:%M:%S-")
                    date_end = datetime.strptime(
                        event_occurance["value2"][:-5], "%Y-%m-%dT%H:%M:%S-")
                    if event_occurance["date_type"] == "date":
                        event.add("dtstart;value=date",
                                  icalendar.vDate(date_start).ical())
                        event.add("dtend;value=date",
                                  icalendar.vDate(date_end).ical())
                    else:
                        event.add("dtstart", date_start)
                        event.add("dtend", date_end)

                    cal.add_component(event)

        self.response.out.write(cal.as_string())
        for retry in range(3):
            if not memcache.add("ksc-calendar", cal.as_string(), 60 * 5):
                logging.warn("Failed to add data to Memcache.")
                time.sleep(0.5)
            else:
                break
Ejemplo n.º 55
0
ogr_kayitli_dersler = kayitli_dersler(ogr_no)  #ogrencinin kayitli dersleri
filtre_fonk = (
    lambda data: (data['kod'], data['sube']) in ogr_kayitli_dersler
)  # sadece ogrencinin kayitli oldugu dersleri almak icin gerekli filtre fonksiyonu
ogr_sinav_takvimi = arasinav(
    filtre_fonk)  #ogrencinin kayitli oldugu derslerin programi

takvim = Calendar()  #takvim olustur
takvim.add('proid', '-//TOBB ETU Arasinav Takvimi//%s//' % ogr_no)
takvim.add('version', '2.0')

for sinav in ogr_sinav_takvimi:
    event = Event()
    event.add('summary', sinav['kod'])
    event.add('description', sinav['ad'])
    event.add('uid', '%s[%d]@st%s' % (sinav['kod'], sinav['sube'], ogr_no))

    if not sinav['saat'] == (u'00:00', u'00:00'):  #saati belli olan sinavlar
        event.add('dtstart', _get_dt(sinav['tarih'], sinav['saat'][0]))
        event.add('dtend', _get_dt(sinav['tarih'], sinav['saat'][1]))
    else:  #kendi saatinde olan sinavlar
        pass  #tum gunluk event eklenecek

    takvim.add_component(event)

f.write(takvim.as_string())
f.close()

# TODO: python2 olayini kesinlestir. gerekli kutuphaneleri dahil et.
# TODO: filtre sorununu coz
Ejemplo n.º 56
0
                except:
                    # ignore events with missing dtstart, dtend or summary
                    DEBUGMSG += ' ! skipped an event with missing dtstart, dtend or summary. likely historic or duplicated event.\n'
                    continue
                newcal.add_component(component)
        # close the existing file
        calfile.close()
    except:
        # if the file was not readable, we need a errormessage ;)
        print MY_SHORTNAME + ': Error: reading file:', sys.exc_info()[1]
        print s

# After the loop, we have all of our data and can write the file now
try:
    f = open(ICS_OUT, 'wb')
    f.write(newcal.as_string())
    f.close()
    DEBUGMSG += 'new calendar written\n'
except:
    print MY_SHORTNAME + ': Error: ', sys.exc_info()[1]

if DEBUG == True:
    try:
        l = open(DEBUGFILE, 'wb')
        l.write(DEBUGMSG)
        l.close()
    except:
        print MY_SHORTNAME + ': Error, unable to write log: ', sys.exc_info(
        )[1]
# all done...