예제 #1
0
def main(argv=None):
    """
    run this as a cron job and execute all
    time based transitions
    """
    db = create_engine('postgres://localhost/bungeni', echo=False)
    component.provideUtility( db, IDatabaseEngine, 'bungeni-db' )
    model.metadata.bind = db
    session = Session()
    component.provideAdapter(
      bungeni.core.workflow.states.WorkflowState,
      (bungeni.core.interfaces.IBungeniContent,))

    component.provideAdapter(
      bungeni.core.workflows.question.QuestionWorkflowAdapter,
      (domain.Question,))

    component.provideAdapter(
      bungeni.core.workflow.states.StateWorkflowInfo,
      (domain.Question,))

    component.provideHandler(
      bungeni.core.workflows.question.workflowTransitionEventDispatcher)
    # add autitor for time based transitions
    #component.provideAdapter(
    #    (bungeni.core.interfaces.IAuditable, bungeni.core.interfaces.IQuestion, ),
    #    (domain.Question, ))
    #component.provideAdapter( audit.objectModified, 
    #(domain.Question, bungeni.core.interfaces.IAuditable, ))
    
    deferAdmissibleQuestions() 
    session.flush()
    session.commit()
예제 #2
0
def queue_time_based_notifications():
    session = Session()
    notification_utl = component.getUtility(INotificationsUtility)
    mq_utility = component.getUtility(IMessageQueueConfig)
    connection = get_mq_connection()
    if not connection:
        return
    channel = connection.channel()
    exchange = str(mq_utility.get_message_exchange())
    notifications = session.query(domain.TimeBasedNotication).filter(
        domain.TimeBasedNotication.notification_date_time <
        datetime.datetime.now()).all()
    for notification in notifications:
        domain_class = notification_utl.get_domain(notification.object_type)
        item = session.query(domain_class).get(notification.object_id)
        if item and item.status == notification.object_status:
            roles = notification_utl.get_time_based_roles(
                domain_class, notification.object_status,
                notification.time_string)
            principal_ids = get_principal_ids(item, roles)
            if principal_ids:
                message = get_message(item, principal_ids)
                message["notification_type"] = "afterstate"
                message["notification_time_string"] = notification.time_string
                dthandler = lambda obj: obj.isoformat() if isinstance(
                    obj, datetime.datetime) else obj
                channel.basic_publish(exchange=exchange,
                                      body=simplejson.dumps(message,
                                                            default=dthandler),
                                      properties=pika.BasicProperties(
                                          content_type="text/plain",
                                          delivery_mode=1),
                                      routing_key="")
        session.delete(notification)
        session.commit()
예제 #3
0
 def __call__(self):
     self.request.response.setHeader("Content-type", "application/pdf")
     self.request.response.setHeader("Content-disposition", 'inline;filename="'
                         + removeSecurityProxy(self.report.report_type) + "_"
                         + removeSecurityProxy(self.report.start_date).strftime("%Y-%m-%d") + '.pdf"')
     
     
     session = Session()
     report = session.query(domain.Report).get(self.report.report_id)
     d = dict([(f.file_title, f.file_data) for f in report.attached_files])
     if "pdf" not in d.keys():
         params = {}
         params["body_text"] = self.cleanupText()
         openofficepath = getUtility(IOpenOfficeConfig).getPath()
         renderer = Renderer(self.odt_file, params, self.tempFileName, pythonWithUnoPath=openofficepath)
         renderer.run()
         f = open(self.tempFileName, "rb")
         doc = f.read()
         f.close()
         os.remove(self.tempFileName)
         attached_file = domain.AttachedFile()
         attached_file.file_title = "pdf"
         attached_file.file_data = doc
         attached_file.language = report.language
         report.attached_files.append(attached_file)
         notify(ObjectCreatedEvent(attached_file))
         session.add(report)
         session.commit()
         return doc
     else:
         return d["pdf"].__str__()
예제 #4
0
 def handle_delete(self, action, data):
     session = Session()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     session.delete(sitting)
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="deleted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" /></data>'
예제 #5
0
    def __call__(self):
        self.request.response.setHeader("Content-type", "application/pdf")
        self.request.response.setHeader(
            "Content-disposition", 'inline;filename="' +
            removeSecurityProxy(self.report.report_type) + "_" +
            removeSecurityProxy(self.report.start_date).strftime("%Y-%m-%d") +
            '.pdf"')

        session = Session()
        report = session.query(domain.Report).get(self.report.report_id)
        d = dict([(f.file_title, f.file_data) for f in report.attached_files])
        if "pdf" not in d.keys():
            params = {}
            params["body_text"] = self.cleanupText()
            openofficepath = getUtility(IOpenOfficeConfig).getPath()
            renderer = Renderer(self.odt_file,
                                params,
                                self.tempFileName,
                                pythonWithUnoPath=openofficepath)
            renderer.run()
            f = open(self.tempFileName, "rb")
            doc = f.read()
            f.close()
            os.remove(self.tempFileName)
            attached_file = domain.AttachedFile()
            attached_file.file_title = "pdf"
            attached_file.file_data = doc
            attached_file.language = report.language
            report.attached_files.append(attached_file)
            notify(ObjectCreatedEvent(attached_file))
            session.add(report)
            session.commit()
            return doc
        else:
            return d["pdf"].__str__()
예제 #6
0
def main(argv=None):
    """
    run this as a cron job and execute all
    time based transitions
    """
    db = create_engine('postgres://localhost/bungeni', echo=False)
    component.provideUtility( db, IDatabaseEngine, 'bungeni-db' )
    model.metadata.bind = db
    session = Session()
    component.provideAdapter(
      bungeni.core.workflows.states.WorkflowState,
      (bungeni.core.interfaces.IBungeniContent,))

    component.provideAdapter(
      bungeni.core.workflows.question.QuestionWorkflowAdapter,
      (domain.Question,))

    component.provideAdapter(
      bungeni.core.workflows.states.StateWorkflowInfo,
      (domain.Question,))

    component.provideHandler(
      bungeni.core.workflows.question.workflowTransitionEventDispatcher)
    # add autitor for time based transitions
    #component.provideAdapter(
    #    (bungeni.core.interfaces.IAuditable, bungeni.core.interfaces.IQuestion, ),
    #    (domain.Question, ))
    #component.provideAdapter( audit.objectModified, 
    #(domain.Question, bungeni.core.interfaces.IAuditable, ))
    
    deferAdmissibleQuestions() 
    session.flush()
    session.commit()
예제 #7
0
 def handle_delete(self, action, data):
     session = Session()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     session.delete(sitting)
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="deleted" sid="' + str(
         data["ids"]) + '" tid="' + str(sitting.sitting_id) + '" /></data>'
예제 #8
0
 def handle_insert(self, action, data):
     session = Session()
     sitting = domain.GroupSitting()
     trusted = removeSecurityProxy(ISchedulingContext(self.context))
     group = session.query(domain.Group).get(trusted.group_id)
     if ("rec_type" not in data.keys()) or (data["rec_type"] == ""):
         sitting.start_date = datetime.datetime.strptime(data["start_date"], '%Y-%m-%d %H:%M')
         sitting.end_date = datetime.datetime.strptime(data["end_date"], '%Y-%m-%d %H:%M')
         sitting.group_id = trusted.group_id
         if "language" in data.keys():
             sitting.language = data["language"]
         if "venue" in data.keys():
             sitting.venue_id = data["venue"]
         session.add(sitting)
         notify(ObjectCreatedEvent(sitting))
         session.commit()
         self.request.response.setHeader('Content-type', 'text/xml')
         return '<data><action type="inserted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" /></data>'
     else:
         try:
             recurrence_start_date = datetime.datetime.strptime(data["start_date"], '%Y-%m-%d %H:%M')
             recurrence_end_date = datetime.datetime.strptime(data["end_date"], '%Y-%m-%d %H:%M')
         except:
             print "Date is not in the correct format"
         year = timedelta(days=365)
         #max end date is one year from now or end_date of the group whichever is sooner
         if (group is not None) and (group.end_date is not None):
             if (datetime.datetime.now() + year) < group.end_date:
                 end = datetime.datetime.now() + year 
             else:
                 end = group.end_date
             if recurrence_end_date > end:
                 recurrence_end_date = end 
         else:
             if recurrence_end_date > (datetime.datetime.now() + year):
                 recurrence_end_date = datetime.datetime.now() + year
         recurrence_type = data["rec_type"]
         length = data["event_length"]
         sitting_length = timedelta(seconds=int(length))
         dates = self.generate_recurrence_dates(recurrence_start_date, recurrence_end_date, recurrence_type)
         output = '<data>'
         for date in dates:
             sitting = domain.GroupSitting()
             sitting.group_id = trusted.group_id
             sitting.start_date = date
             sitting.end_date = date + sitting_length
             sitting.status = None
             if "language" in data.keys():
                 sitting.language = data["language"]
             if "venue" in data.keys():
                 sitting.venue_id = data["venue"]
             session.add(sitting)
             notify(ObjectCreatedEvent(sitting))
             output = output+'<action type="inserted" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" />'
         session.commit()
         output = output + '</data>'
         self.request.response.setHeader('Content-type', 'text/xml')
         return output
예제 #9
0
    def handle_add_save(self, action, data):
        """After succesful creation of translation, redirect to the
        view."""
        for key in data.keys():
            if isinstance(data[key], str):
                data[key] = unescape(data[key])
        #url = url.absoluteURL(self.context, self.request)
        #language = get_language_by_name(data["language"])["name"]
        session = Session()
        trusted = removeSecurityProxy(self.context)
        mapper = rdb.orm.object_mapper(trusted)
        pk = getattr(trusted, mapper.primary_key[0].name)

        current_translation = get_translation_for(self.context,
                                                  data["language"])
        if current_translation:
            for translation in current_translation:
                session.delete(translation)

        for form_field in data.keys():
            if form_field == "language":
                continue
            translation = domain.ObjectTranslation()
            translation.object_id = pk
            translation.object_type = trusted.__class__.__name__
            translation.field_name = form_field
            translation.lang = data["language"]
            translation.field_text = data[form_field]
            session.add(translation)
        session.flush()
        session.commit()
        session.close()

        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #versions = IVersioned(self.context)
        #version = versions.create("'%s' translation added" % language)

        # reset workflow state
        #version.status = None
        #IWorkflowInfo(version).fireTransition("-draft_translation")
        # redefine form context and proceed with edit action
        #self.setUpAdapters(version)
        #handle_edit_action(self, action, data)

        # commit version such that it gets a version id
        #transaction.commit()

        #if not self._next_url:
        #    self._next_url = ( \
        #        "%s/versions/%s" % (url, stringKey(version)) + \
        #        "?portal_status_message=Translation added")

        self._finished_add = True
예제 #10
0
 def resolve(self, id): 
     class_path, oid = id.split('-', 1)
     domain_class = resolve.resolve(class_path)
     session = Session()
     value_key = container.valueKey(oid)
     obj = session.query(domain_class).get(value_key)
     if not obj:
         session.commit()
         obj = session.query(domain_class).get(value_key)
     return obj
예제 #11
0
    def handle_add_save(self, action, data):
        """After succesful creation of translation, redirect to the
        view."""
        for key in data.keys():
            if isinstance(data[key], str):
                data[key] = unescape(data[key])
        #url = url.absoluteURL(self.context, self.request)
        #language = get_language_by_name(data["language"])["name"]
        session = Session()
        trusted = removeSecurityProxy(self.context)
        mapper = rdb.orm.object_mapper(trusted)
        pk = getattr(trusted, mapper.primary_key[0].name)

        current_translation = get_translation_for(self.context, data["language"])
        if current_translation:
            for translation in current_translation:
                session.delete(translation)

        for form_field in data.keys():
            if form_field == "language":
                continue
            translation = domain.ObjectTranslation()
            translation.object_id = pk
            translation.object_type = trusted.__class__.__name__
            translation.field_name = form_field
            translation.lang = data["language"]
            translation.field_text = data[form_field]
            session.add(translation)
        session.flush()
        session.commit()
        session.close()
        
        # !+EVENT_DRIVEN_CACHE_INVALIDATION(mr, mar-2011) no translate event
        # invalidate caches for this domain object type
        invalidate_caches_for(trusted.__class__.__name__, "translate")

        #versions = IVersioned(self.context)
        #version = versions.create("'%s' translation added" % language)

        # reset workflow state
        #version.status = None
        #IWorkflowInfo(version).fireTransition("-draft_translation")
        # redefine form context and proceed with edit action
        #self.setUpAdapters(version)
        #handle_edit_action(self, action, data)

        # commit version such that it gets a version id
        #transaction.commit()

        #if not self._next_url:
        #    self._next_url = ( \
        #        "%s/versions/%s" % (url, stringKey(version)) + \
        #        "?portal_status_message=Translation added")

        self._finished_add = True
예제 #12
0
 def handle_generate_takes(self, action, data):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     takes = session.query(domain.Take).filter(
         domain.Take.sitting_id == trusted.sitting_id)
     for t in takes:
         session.delete(t)
     
     sitting = trusted
     current_start_time = sitting.start_date
     sitting_duration = sitting.end_date - sitting.start_date
     take_duration = timedelta(minutes=int(data["duration"]))
     assigned_reporters = get_assigned_staff(self.context, "Reporter")
     assigned_readers = get_assigned_staff(self.context, "Reader")
     assigned_editors = get_assigned_staff(self.context, "Editor")
     c_reporter = 0 
     c_reader = 0
     c_editor = 0
     
     while sitting_duration > timedelta(minutes=0):
         take = domain.Take()
         take.sitting_id = sitting.sitting_id
         if (sitting_duration - take_duration) > timedelta(minutes=0):
             sitting_duration = sitting_duration - take_duration
             take.start_date = current_start_time
             take.end_date = take.start_date + take_duration
             current_start_time = take.end_date
         else:
             take.start_date = current_start_time
             take.end_date = take.start_date + sitting_duration
             sitting_duration = timedelta(minutes=0)
         if c_reporter > len(assigned_reporters)-1:
             c_reporter = 0
             take.reporter_id = assigned_reporters[c_reporter]
         else:
             take.reporter_id = assigned_reporters[c_reporter]
         c_reporter = c_reporter + 1
         
         if c_reader > len(assigned_readers)-1:
             c_reader = 0
             take.reader_id = assigned_readers[c_reader]
         else:
             take.reader_id = assigned_readers[c_reader]
         c_reader = c_reader + 1
         
         if c_editor > len(assigned_editors)-1:
             c_editor = 0
             take.editor_id = assigned_editors[c_editor]
         else:
             take.editor_id = assigned_editors[c_editor]
         c_editor = c_editor + 1
         session.add(take)
     session.commit()
     self.request.response.redirect('./takes')
예제 #13
0
def group_sitting_created(ob, event):
    '''
    Recieves notification that a new sitting has been created and creates
    a hansard for it.
    '''
    session = Session()
    ob = removeSecurityProxy(ob)
    hansard = domain.Hansard()
    hansard.sitting_id = ob.sitting_id
    session.add(hansard)
    session.commit()
예제 #14
0
    def handle_generate_takes(self, action, data):
        session = Session()
        trusted = removeSecurityProxy(self.context)
        takes = session.query(
            domain.Take).filter(domain.Take.sitting_id == trusted.sitting_id)
        for t in takes:
            session.delete(t)

        sitting = trusted
        current_start_time = sitting.start_date
        sitting_duration = sitting.end_date - sitting.start_date
        take_duration = timedelta(minutes=int(data["duration"]))
        assigned_reporters = get_assigned_staff(self.context, "Reporter")
        assigned_readers = get_assigned_staff(self.context, "Reader")
        assigned_editors = get_assigned_staff(self.context, "Editor")
        c_reporter = 0
        c_reader = 0
        c_editor = 0

        while sitting_duration > timedelta(minutes=0):
            take = domain.Take()
            take.sitting_id = sitting.sitting_id
            if (sitting_duration - take_duration) > timedelta(minutes=0):
                sitting_duration = sitting_duration - take_duration
                take.start_date = current_start_time
                take.end_date = take.start_date + take_duration
                current_start_time = take.end_date
            else:
                take.start_date = current_start_time
                take.end_date = take.start_date + sitting_duration
                sitting_duration = timedelta(minutes=0)
            if c_reporter > len(assigned_reporters) - 1:
                c_reporter = 0
                take.reporter_id = assigned_reporters[c_reporter]
            else:
                take.reporter_id = assigned_reporters[c_reporter]
            c_reporter = c_reporter + 1

            if c_reader > len(assigned_readers) - 1:
                c_reader = 0
                take.reader_id = assigned_readers[c_reader]
            else:
                take.reader_id = assigned_readers[c_reader]
            c_reader = c_reader + 1

            if c_editor > len(assigned_editors) - 1:
                c_editor = 0
                take.editor_id = assigned_editors[c_editor]
            else:
                take.editor_id = assigned_editors[c_editor]
            c_editor = c_editor + 1
            session.add(take)
        session.commit()
        self.request.response.redirect('./takes')
예제 #15
0
 def callback(channel, method, properties, body):
     #channel.confirm_delivery()
     notification_utl = component.getUtility(INotificationsUtility)
     exchange = str(mq_utility.get_message_exchange())
     message = simplejson.loads(body)
     domain_class = notification_utl.get_domain(
         message["document_type"])
     session = Session()
     if domain_class and message["document_id"]:
         document = session.query(domain_class).get(message["document_id"])
         if document:
             # first we handle the transition based notifications
             transition_roles = notification_utl.get_transition_based_roles(
                 domain_class, message["destination"]
             )
             transition_principal_ids = get_principal_ids(
                 document, transition_roles)
             if transition_principal_ids:
                 mes = get_message(document, transition_principal_ids)
                 mes["notification_type"] = "onstate"
                 dthandler = lambda obj: obj.isoformat() if isinstance(
                     obj, datetime.datetime) else obj
                 #channel_conf = 
                 channel.basic_publish(
                     exchange=exchange,
                     body=simplejson.dumps(mes, default=dthandler),
                     properties=pika.BasicProperties(
                         content_type="text/plain",
                         delivery_mode=1
                     ),
                     routing_key=""
                 )
                 #if channel_conf:
                 #   log.info("Message published for exchange %r", exchange)
                 #else:
                 #   log.error("Message publication failed for exchange %s and message %s" % (exchange, mes))
             # then we handle the time based notifications
             time_roles = notification_utl.get_time_based_time_and_roles(
                 domain_class, message["destination"]
             )
             for time_string, roles in time_roles.iteritems():
                 time_ntf = domain.TimeBasedNotication()
                 time_ntf.object_id = message["document_id"]
                 time_ntf.object_type = message["document_type"]
                 time_ntf.object_status = message["destination"]
                 time_ntf.time_string = time_string
                 time_ntf.notification_date_time = notification_time(
                     time_string)
                 session.add(time_ntf)
     # we commit manually here as this code is not executed in a zope
     # transaction
     session.commit()
     session.close()
     channel.basic_ack(delivery_tag=method.delivery_tag)
예제 #16
0
def group_sitting_created(ob, event):
    '''
    Recieves notification that a new sitting has been created and creates
    a hansard for it.
    '''
    session = Session()
    ob = removeSecurityProxy(ob)
    hansard = domain.Hansard()
    hansard.sitting_id = ob.sitting_id
    session.add(hansard)
    session.commit()
예제 #17
0
 def __call__(self):
     obj = self.request.form['obj[]']
     session = Session()
     if self.context.status == "draft_agenda":
         for i in range(0, len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'planned_order', i + 1)
     elif self.context.status == "draft_minutes":
         for i in range(0, len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'real_order', i + 1)
     session.commit()
예제 #18
0
 def __call__(self):
     obj = self.request.form['obj[]']
     session = Session()
     if self.context.status == "draft_agenda":
         for i in range(0,len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'planned_order', i+1)
     elif self.context.status == "draft_minutes":
         for i in range(0,len(obj)):
             sch = session.query(domain.ItemSchedule).get(obj[i])
             setattr(sch, 'real_order', i+1)
     session.commit()
예제 #19
0
 def handle_delete(self, action, data):
     session = Session()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     # set extra data needed by template
     self.template_data = []
     if sitting is not None:
         self.request.response.setHeader('Content-type', 'text/xml')
         self.template_data.append({"sitting_id": sitting.sitting_id, 
                                    "action": "deleted",
                                    "ids": data["ids"]})
         session.delete(sitting)
         session.commit()
         return self.template()
예제 #20
0
    def handle_save(self, action, data):
        report = domain.Report()
        session = Session()
        report.body_text = data["body_text"]
        report.start_date = data["start_date"]
        report.end_date = data["end_date"]
        report.note = data["note"]
        report.report_type = data["report_type"]
        report.short_name = data["report_type"]
        owner_id = get_db_user_id()
        '''!+TODO(Miano, 18/08/2010) The admin user is currently not a db user
            thus the line above returns None when the admin publishes a report.
            to go around this if it returns None, just query the db for users
            and set the owner id to be the first result'''
        if owner_id is not None:
            report.owner_id = owner_id
        else:
            query = session.query(domain.User)
            results = query.all()
            report.owner_id = results[0].user_id
        report.language = "en"
        report.created_date = datetime.datetime.now()
        report.group_id = self.context.group_id
        session.add(report)
        notify(ObjectCreatedEvent(report))
        # !+INVALIDATE(mr, sep-2010)
        container.invalidate_caches_for("Report", "add")
        if "sittings" in data.keys():
            try:
                ids = data["sittings"].split(",")
                for id_number in ids:
                    sit_id = int(id_number)
                    sitting = session.query(domain.GroupSitting).get(sit_id)
                    sr = domain.SittingReport()
                    sr.report = report
                    sr.sitting = sitting
                    session.add(sr)
                    # !+INVALIDATE(mr, sep-2010) via an event...
                    container.invalidate_caches_for("SittingReport", "add")
            except:
                #if no sittings are present in report or some other error occurs
                pass
        session.commit()

        if IGroupSitting.providedBy(self.context):
            back_link = "./schedule"
        elif ISchedulingContext.providedBy(self.context):
            back_link = "./"
        else:
            raise NotImplementedError
        self.request.response.redirect(back_link)
예제 #21
0
 def handle_save(self, action, data):
     report = domain.Report()
     session = Session()
     report.body_text = data["body_text"]
     report.start_date = data["start_date"]
     report.end_date = data["end_date"]
     report.note = data["note"]
     report.short_name = report.short_name = data["short_name"]
     owner_id = get_db_user_id()
     '''!+TODO(Miano, 18/08/2010) The admin user is currently not a db user
         thus the line above returns None when the admin publishes a report.
         to go around this if it returns None, just query the db for users
         and set the owner id to be the first result'''
     if owner_id is not None:
         report.owner_id = owner_id
     else:
         query = session.query(domain.User)
         results = query.all()
         report.owner_id = results[0].user_id
     # TODO get language from config
     report.language = "en"
     report.created_date = datetime.datetime.now()
     report.group_id = self.context.group_id
     session.add(report)
     notify(ObjectCreatedEvent(report))
     # !+INVALIDATE(mr, sep-2010)
     container.invalidate_caches_for("Report", "add")
     if "sittings" in data.keys():
         try:
             ids = data["sittings"].split(",")
             for id_number in ids:
                 sit_id = int(id_number)
                 sitting = session.query(domain.GroupSitting).get(sit_id)
                 sr = domain.SittingReport()
                 sr.report = report
                 sr.sitting = sitting
                 session.add(sr)
                 # !+INVALIDATE(mr, sep-2010) via an event...
                 container.invalidate_caches_for("SittingReport", "add")
         except:
             #if no sittings are present in report or some other error occurs
             pass
     session.commit()
     
     if IGroupSitting.providedBy(self.context):
         back_link = "./schedule"
     elif ISchedulingContext.providedBy(self.context):
         back_link = "./"
     else:
         raise NotImplementedError
     self.request.response.redirect(back_link)
예제 #22
0
 def __call__(self):
     obj = self.request.form['obj[]']
     '''container = self.context
     schedulings = container.item_schedule
     
     for s in schedulings:
         print "s=>", s, s.planned_order
     for order, id_number in enumerate(obj):
         print "asdfasdf", order, id_number'''
     session = Session()
     for i in range(0, len(obj)):
         sch = session.query(domain.ItemSchedule).get(obj[i])
         setattr(sch, 'planned_order', i + 1)
     session.commit()
예제 #23
0
 def handle_update(self, action, data):
     session = Session()
     sitting = domain.GroupSitting()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     sitting.start_date = data["start_date"]
     sitting.end_date = data["end_date"]
     if "language" in data.keys():
         sitting.language = data["language"]
     if "venue" in data.keys():
         sitting.venue_id = data["venue"]
     session.update(sitting)
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="updated" sid="'+str(data["ids"])+'" tid="'+str(sitting.sitting_id)+'" /></data>'
예제 #24
0
 def __call__(self):
     obj = self.request.form['obj[]']
     '''container = self.context
     schedulings = container.item_schedule
     
     for s in schedulings:
         print "s=>", s, s.planned_order
     for order, id_number in enumerate(obj):
         print "asdfasdf", order, id_number'''
     session = Session()
     for i in range(0,len(obj)):
         sch = session.query(domain.ItemSchedule).get(obj[i])
         setattr(sch, 'planned_order', i+1)
     session.commit()
예제 #25
0
 def callback(channel, method, properties, body):
     #channel.confirm_delivery()
     notification_utl = component.getUtility(INotificationsUtility)
     exchange = str(mq_utility.get_message_exchange())
     message = simplejson.loads(body)
     domain_class = notification_utl.get_domain(message["document_type"])
     session = Session()
     if domain_class and message["document_id"]:
         document = session.query(domain_class).get(message["document_id"])
         if document:
             # first we handle the transition based notifications
             transition_roles = notification_utl.get_transition_based_roles(
                 domain_class, message["destination"])
             transition_principal_ids = get_principal_ids(
                 document, transition_roles)
             if transition_principal_ids:
                 mes = get_message(document, transition_principal_ids)
                 mes["notification_type"] = "onstate"
                 dthandler = lambda obj: obj.isoformat() if isinstance(
                     obj, datetime.datetime) else obj
                 #channel_conf =
                 channel.basic_publish(exchange=exchange,
                                       body=simplejson.dumps(
                                           mes, default=dthandler),
                                       properties=pika.BasicProperties(
                                           content_type="text/plain",
                                           delivery_mode=1),
                                       routing_key="")
                 #if channel_conf:
                 #   log.info("Message published for exchange %r", exchange)
                 #else:
                 #   log.error("Message publication failed for exchange %s and message %s" % (exchange, mes))
             # then we handle the time based notifications
             time_roles = notification_utl.get_time_based_time_and_roles(
                 domain_class, message["destination"])
             for time_string, roles in time_roles.iteritems():
                 time_ntf = domain.TimeBasedNotication()
                 time_ntf.object_id = message["document_id"]
                 time_ntf.object_type = message["document_type"]
                 time_ntf.object_status = message["destination"]
                 time_ntf.time_string = time_string
                 time_ntf.notification_date_time = notification_time(
                     time_string)
                 session.add(time_ntf)
     # we commit manually here as this code is not executed in a zope
     # transaction
     session.commit()
     session.close()
     channel.basic_ack(delivery_tag=method.delivery_tag)
예제 #26
0
 def handle_update(self, action, data):
     session = Session()
     sitting = domain.GroupSitting()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     sitting.start_date = data["start_date"]
     sitting.end_date = data["end_date"]
     if "language" in data.keys():
         sitting.language = data["language"]
     if "venue" in data.keys():
         sitting.venue_id = data["venue"]
     session.update(sitting)
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return '<data><action type="updated" sid="' + str(
         data["ids"]) + '" tid="' + str(sitting.sitting_id) + '" /></data>'
예제 #27
0
 def handle_update(self, action, data):
     session = Session()
     sitting = domain.GroupSitting()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     sitting.start_date = data["start_date"]
     sitting.end_date = data["end_date"]
     if "language" in data.keys():
         sitting.language = data["language"]
     if "venue" in data.keys():
         sitting.venue_id = data["venue"]
     # set extra data needed by template
     session.update(sitting)
     self.template_data.append({"sitting_id": sitting.sitting_id, 
                                 "action": "inserted",
                                 "ids": data["ids"]})
     session.commit()
     self.request.response.setHeader('Content-type', 'text/xml')
     return self.template()
예제 #28
0
 def handle_post(self, action, data):
     doc = etree.fromstring(data["xml"])
     session = Session()         
     for take in doc.iterchildren('take'):
         sitting_id = take.get("sittingID")
         t_start_time = take.get("startTime").split(":")
         take_start_time = None
          
         if (len(t_start_time) == 3):
             take_start_time = timedelta(hours=int(t_start_time[0]),
                                         minutes=int(t_start_time[1]),
                                         seconds=int(t_start_time[2]))
         if (sitting_id != ""):
             sitting = session.query(bungeni_domain.GroupSitting).get(int(sitting_id))
         print "Sitting ID",sitting_id, "\n";
         for speech in take.iterchildren("speech"):
             s_start_time = speech.get("startTime").split(":")
             s_end_time = speech.get("endTime").split(":")
             speech_start_time = None
             speech_end_time = None
             if (len(s_start_time) == 3):
                 speech_start_time = timedelta(hours=int(s_start_time[0]),
                                               minutes=int(s_start_time[1]),
                                               seconds=int(s_start_time[2]))
             if (len(s_end_time) == 3):
                 speech_end_time = timedelta(hours=int(s_end_time[0]),
                                             minutes=int(s_end_time[1]),
                                             seconds=int(s_end_time[2]))
             if ( (speech_start_time is not None) and
                  (speech_end_time is not None) and
                  (take_start_time is not None) and
                  (sitting is not None)):
                 transcript = domain.Transcript()
                 transcript.start_date = sitting.start_date+take_start_time + speech_start_time
                 transcript.end_date = sitting.start_date+take_start_time + speech_end_time
                 if speech.get("person_id") == "":
                     transcript.person_name = speech.get("person_name")
                 else:
                     transcript.person_id = int(speech.get("person_id"))
                 transcript.text = speech.text
                 transcript.sitting_id = sitting.sitting_id
                 session.add(transcript)
     session.commit()
예제 #29
0
 def handle_save(self, action, data):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     sitting = session.query(domain.GroupSitting).get(trusted.sitting_id)
     if sitting.hansard.media_paths is None:
         media_paths = domain.HansardMediaPaths()
         media_paths.web_optimised_video_path =  data['web_optimised_video_path']    
         media_paths.audio_only_path =  data['audio_only_path']
         media_paths.high_quality_video_path =  data['high_quality_video_path'] 
         media_paths.hansard_id = sitting.hansard.hansard_id
         session.add(media_paths)
     else:
         sitting.hansard.media_paths.web_optimised_video_path =  data['web_optimised_video_path']    
         sitting.hansard.media_paths.audio_only_path =  data['audio_only_path']
         sitting.hansard.media_paths.high_quality_video_path =  data['high_quality_video_path'] 
         session.update(sitting)
     session.commit()
     self._next_url = absoluteURL(self.context, self.request)+"/hansard"
     self.request.response.redirect(self._next_url)
예제 #30
0
def add_admin(login, password, email_address):
    session = Session()
    user = domain.User()
    # The names are hardcorded so that they unambigously refer
    # to the administrator ie. the logs will show "System Administrator" and not
    # 'John Doe'.
    user.first_name = _(u"System")
    user.last_name = _(u"Administrator")
    user.login = login
    user._password = password
    user.gender = "M"
    user.language = "en"
    user.email = email_address
    user.is_admin = True
    user.active_p = "A"  # status, normally automatically set by the workflow
    session.add(user)
    admin_user = domain.AdminUser()
    admin_user.user = user
    session.add(admin_user)
    session.commit()
예제 #31
0
 def handle_assignment(self, action, data):
     session = Session()
     session.query(domain.Assignment).filter(domain.Assignment.sitting_id == self.context.sitting_id).delete()
     for editor_id in data["editors"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = editor_id
         session.add(assignment)
     for reader_id in data["readers"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reader_id
         session.add(assignment)
     for reporter_id in data["reporters"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reporter_id
         session.add(assignment)
     session.commit()
     self.request.response.redirect('./hansard')    
예제 #32
0
 def handle_update(self, action, data):
     session = Session()
     self.template_data = []
     sitting = domain.GroupSitting()
     sitting = session.query(domain.GroupSitting).get(data["ids"])
     sitting.start_date = data["start_date"].replace(tzinfo=None)
     sitting.end_date = data["end_date"].replace(tzinfo=None)
     if "language" in data.keys():
         sitting.language = data["language"]
     if "venue" in data.keys():
         sitting.venue_id = data["venue"]
     # set extra data needed by template
     session.update(sitting)
     notify(ObjectModifiedEvent(sitting))
     self.template_data.append(
         {"group_sitting_id": sitting.group_sitting_id, "action": "inserted", "ids": data["ids"]}
     )
     session.commit()
     self.request.response.setHeader("Content-type", "text/xml")
     return self.xml_template()
예제 #33
0
def add_admin(login, password, email_address):                
    session = Session()
    user = domain.User()
    # The names are hardcorded so that they unambigously refer
    # to the administrator ie. the logs will show "System Administrator" and not
    # 'John Doe'. 
    user.first_name = _(u"System")
    user.last_name = _(u"Administrator")
    user.login = login
    user._password = password
    user.gender = "M"
    user.language = "en"
    user.email=email_address
    user.is_admin = True
    user.active_p = "A" # status, normally automatically set by the workflow
    session.add(user)
    admin_user = domain.AdminUser()
    admin_user.user = user
    session.add(admin_user)
    session.commit()
예제 #34
0
 def __call__(self):
     self.request.response.setHeader("Content-type",
                                     "application/vnd.oasis.opendocument.text")
     self.request.response.setHeader("Content-disposition",
                                     'inline;filename="' +
                                     removeSecurityProxy(self.report.short_name) 
                                     + "_" + removeSecurityProxy(self.report.start_date) \
                                     .strftime("%Y-%m-%d") + '.odt"')
     session = Session()
     report = session.query(domain.Report).get(self.report.report_id)
     d = dict([(f.file_title, f.file_data) for f in report.attached_files])
     if "odt" not in d.keys():
         params = {}
         params["body_text"] = self.cleanupText()
         renderer = Renderer(self.odt_file, params, self.tempFileName)
         renderer.run()
         f = open(self.tempFileName, "rb")
         doc = f.read()
         f.close()
         os.remove(self.tempFileName)
         file_type = session.query(domain.AttachedFileType) \
                            .filter(domain.AttachedFileType \
                                             .attached_file_type_name 
                                         == "annex") \
                            .first()
         if file_type is None:
             file_type = domain.AttachedFileType
             file_type.attached_file_type_name = "annex"
             file_type.language = report.language
         attached_file = domain.AttachedFile()
         attached_file.file_title = "odt"
         attached_file.file_data = doc
         attached_file.language = report.language
         attached_file.type = file_type
         report.attached_files.append(attached_file)
         notify(ObjectCreatedEvent(attached_file))
         session.add(report)
         session.commit()
         return doc
     else:
         return d["odt"].__str__()
예제 #35
0
def default_reports(sitting, event):
    if sitting.status in ("published_agenda", "published_minutes"):
        sitting = removeSecurityProxy(sitting)
        sittings = []
        sittings.append(sitting)
        report = domain.Report()
        session = Session()
        #!+REPORTS(miano, dec-2010) using test request here is not quite right
        # TODO : fix this.
        from zope.publisher.browser import TestRequest
        report.start_date = sitting.start_date
        report.end_date = sitting.end_date
        # The owner ID is the ID of the user that performed the last workflow
        # change
        for change in reversed(sitting.changes):
            if change.action == "workflow":
                owner_id = change.user_id
                break
        assert owner_id is not None, _("No user is defined. Are you logged in as Admin?")
        report.owner_id = owner_id
        report.language = get_default_language()
        report.created_date = datetime.datetime.now()
        report.group_id = sitting.group_id
        if sitting.status == 'published_agenda':
            report.short_name = "Sitting Agenda"
            drc = DefaultReportContent(sittings, report.short_name, False)
            report.body_text = DefaultReportView(drc, TestRequest())()
        elif sitting.status == 'published_minutes':
            report.short_name = "Sitting Votes and Proceedings"
            drc = DefaultReportContent(sittings, report.short_name, True)
            report.body_text = DefaultReportView(drc, TestRequest())()
        session.add(report)
        notify(ObjectCreatedEvent(report))
        sr = domain.SittingReport()
        sr.report = report
        sr.sitting = sitting
        session.add(sr)
        notify(ObjectCreatedEvent(sr))
        session.commit()
        container.invalidate_caches_for("Report", "add")
        container.invalidate_caches_for("SittingReport", "add")
 def documentData(self, cached=False):
     """Either generate ODT/PDF doc or retrieve from attached files of the
     content item. Cached should only be True for content items that
     are immutable eg. reports."""
     #TODO : Either generate a hash of a mutable content item and store it 
     # with the odt/pdf doc or track changes to a doc
     tempFileName = os.path.dirname(__file__) + "/tmp/%f.%s" % (
                                             time.time(),self.document_type)
     if cached:
         session = Session()
         d = [f.file_title for f in self.document.attached_files]
         if self.document_type not in d:
             file_type = session.query(domain.AttachedFileType) \
                            .filter(domain.AttachedFileType \
                                             .attached_file_type_name 
                                         == "system") \
                            .first()
             if file_type is None:
                 file_type = domain.AttachedFileType()
                 file_type.attached_file_type_name = "system"
                 file_type.language = self.document.language
                 session.add(file_type)
                 session.flush()
             attached_file = domain.AttachedFile()
             attached_file.file_title = self.document_type
             attached_file.file_data = self.generateDoc()
             attached_file.language = self.document.language
             attached_file.type = file_type
             self.document.attached_files.append(attached_file)
             session.add(self.document)
             session.commit()
             notify(ObjectCreatedEvent(attached_file))
         for f in self.document.attached_files:
             if f.file_title == self.document_type: 
                 self.setHeader(self.document_type)
                 return f.file_data.__str__()
         #If file is not found
         return self.error_template()
     else:
         self.setHeader(self.document_type)
         return self.generateDoc()
예제 #37
0
 def documentData(self, cached=False):
     """Either generate ODT/PDF doc or retrieve from attached files of the
     content item. Cached should only be True for content items that
     are immutable eg. reports."""
     #TODO : Either generate a hash of a mutable content item and store it
     # with the odt/pdf doc or track changes to a doc
     tempFileName = os.path.dirname(
         __file__) + "/tmp/%f.%s" % (time.time(), self.document_type)
     if cached:
         session = Session()
         d = [f.file_title for f in self.document.attached_files]
         if self.document_type not in d:
             file_type = session.query(domain.AttachedFileType) \
                            .filter(domain.AttachedFileType \
                                             .attached_file_type_name
                                         == "system") \
                            .first()
             if file_type is None:
                 file_type = domain.AttachedFileType()
                 file_type.attached_file_type_name = "system"
                 file_type.language = self.document.language
                 session.add(file_type)
                 session.flush()
             attached_file = domain.AttachedFile()
             attached_file.file_title = self.document_type
             attached_file.file_data = self.generateDoc()
             attached_file.language = self.document.language
             attached_file.type = file_type
             self.document.attached_files.append(attached_file)
             session.add(self.document)
             session.commit()
             notify(ObjectCreatedEvent(attached_file))
         for f in self.document.attached_files:
             if f.file_title == self.document_type:
                 self.setHeader(self.document_type)
                 return f.file_data.__str__()
         #If file is not found
         return self.error_template()
     else:
         self.setHeader(self.document_type)
         return self.generateDoc()
예제 #38
0
def default_reports(sitting, event):
    if sitting.status in ("published_agenda", "published_minutes"):
        sitting = removeSecurityProxy(sitting)
        sittings = []
        sittings.append(sitting)
        report = domain.Report()
        session = Session()
        #!+REPORTS(miano, dec-2010) using test request here is not quite right
        # TODO : fix this.
        from zope.publisher.browser import TestRequest
        report.start_date = sitting.start_date
        report.end_date = sitting.end_date
        # The owner ID is the ID of the user that performed the last workflow
        # change
        for change in reversed(sitting.changes):
            if change.action == "workflow":
                owner_id = change.user_id
                break
        assert owner_id is not None, _(
            "No user is defined. Are you logged in as Admin?")
        report.owner_id = owner_id
        report.language = get_default_language()
        report.created_date = datetime.datetime.now()
        report.group_id = sitting.group_id
        if sitting.status == 'published_agenda':
            report.short_name = _(u"Sitting Agenda")
            drc = DefaultReportContent(sittings, report.short_name, False)
            report.body_text = DefaultReportView(drc, TestRequest())()
        elif sitting.status == 'published_minutes':
            report.short_name = _(u"Sitting Votes and Proceedings")
            drc = DefaultReportContent(sittings, report.short_name, True)
            report.body_text = DefaultReportView(drc, TestRequest(), False)()
        session.add(report)
        session.flush()
        notify(ObjectCreatedEvent(report))
        sr = domain.SittingReport()
        sr.report = report
        sr.sitting = sitting
        session.add(sr)
        session.commit()
        notify(ObjectCreatedEvent(sr))
예제 #39
0
 def handle_assignment(self, action, data):
     session = Session()
     session.query(domain.Assignment).filter(
         domain.Assignment.sitting_id == self.context.sitting_id).delete()
     for editor_id in data["editors"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = editor_id
         session.add(assignment)
     for reader_id in data["readers"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reader_id
         session.add(assignment)
     for reporter_id in data["reporters"]:
         assignment = domain.Assignment()
         assignment.sitting_id = self.context.sitting_id
         assignment.staff_id = reporter_id
         session.add(assignment)
     session.commit()
     self.request.response.redirect('./hansard')
예제 #40
0
    def handle_delete(self, action, data):
        count = self.delete_subobjects()
        container = self.context.__parent__
        trusted = removeSecurityProxy(self.context)
        session = Session()
        session.delete(trusted)
        count += 1

        try:
            session.commit()
        except IntegrityError, e:
            # this should not happen in production; it's a critical
            # error, because the transaction might have failed in the
            # second phase of the commit
            session.rollback()
            log.critical(e)

            self.status = _(u"Could not delete item due to "
                            "database integrity error")

            return self.render()
예제 #41
0
    def handle_delete(self, action, data):
        count = self.delete_subobjects()
        container = self.context.__parent__
        trusted = removeSecurityProxy(self.context)
        session = Session()
        session.delete(trusted)
        count += 1

        try:
            session.commit()
        except IntegrityError, e:
            # this should not happen in production; it's a critical
            # error, because the transaction might have failed in the
            # second phase of the commit
            session.rollback()
            log.critical(e)

            self.status = _(u"Could not delete item due to "
                            "database integrity error")

            return self.render()
예제 #42
0
 def handle_save(self, action, data):
     report = domain.Report()
     session = Session()
     report.body_text = data["body_text"]
     report.start_date = data["start_date"]
     report.end_date = data["end_date"]
     report.note = data["note"]
     report.short_name = data["short_name"]
     report.owner_id = get_db_user_id()
     report.language = get_default_language()
     report.created_date = datetime.datetime.now()
     if not hasattr(self.context, "group_id"):
         report.group_id = ISchedulingContext(self.context).group_id
     else:
         report.group_id = self.context.group_id
     session.add(report)
     session.flush()
     notify(ObjectCreatedEvent(report))
     if "sittings" in data.keys():
         try:
             ids = data["sittings"].split(",")
             for id_number in ids:
                 sit_id = int(id_number)
                 sitting = session.query(domain.GroupSitting).get(sit_id)
                 sr = domain.SittingReport()
                 sr.report = report
                 sr.sitting = sitting
                 session.add(sr)
                 notify(ObjectCreatedEvent(report))
         except:
             #if no sittings are present in report or some other error occurs
             pass
     session.commit()
     
     if IGroupSitting.providedBy(self.context):
         back_link = "./schedule"
     else:
         back_link = "./"
     self.request.response.redirect(back_link)
예제 #43
0
    def handle_save(self, action, data):
        report = domain.Report()
        session = Session()
        report.body_text = data["body_text"]
        report.start_date = data["start_date"]
        report.end_date = data["end_date"]
        report.note = data["note"]
        report.short_name = data["short_name"]
        report.owner_id = get_db_user_id()
        report.language = get_default_language()
        report.created_date = datetime.datetime.now()
        if not hasattr(self.context, "group_id"):
            report.group_id = ISchedulingContext(self.context).group_id
        else:
            report.group_id = self.context.group_id
        session.add(report)
        session.flush()
        notify(ObjectCreatedEvent(report))
        if "sittings" in data.keys():
            try:
                ids = data["sittings"].split(",")
                for id_number in ids:
                    sit_id = int(id_number)
                    sitting = session.query(domain.GroupSitting).get(sit_id)
                    sr = domain.SittingReport()
                    sr.report = report
                    sr.sitting = sitting
                    session.add(sr)
                    notify(ObjectCreatedEvent(report))
            except:
                #if no sittings are present in report or some other error occurs
                pass
        session.commit()

        if IGroupSitting.providedBy(self.context):
            back_link = "./schedule"
        else:
            back_link = "./"
        self.request.response.redirect(back_link)
예제 #44
0
def queue_time_based_notifications():
    session = Session()
    notification_utl = component.getUtility(INotificationsUtility)
    mq_utility = component.getUtility(IMessageQueueConfig)
    connection = get_mq_connection()
    if not connection:
        return
    channel = connection.channel()
    exchange = str(mq_utility.get_message_exchange())
    notifications = session.query(domain.TimeBasedNotication).filter(
        domain.TimeBasedNotication.notification_date_time <
        datetime.datetime.now()).all()
    for notification in notifications:
        domain_class = notification_utl.get_domain(
            notification.object_type)
        item = session.query(domain_class).get(notification.object_id)
        if item and item.status == notification.object_status:
            roles = notification_utl.get_time_based_roles(
                domain_class, notification.object_status,
                notification.time_string)
            principal_ids = get_principal_ids(item, roles)
            if principal_ids:
                message = get_message(item, principal_ids)
                message["notification_type"] = "afterstate"
                message["notification_time_string"] = notification.time_string
                dthandler = lambda obj: obj.isoformat() if isinstance(
                    obj, datetime.datetime) else obj
                channel.basic_publish(
                    exchange=exchange,
                    body=simplejson.dumps(message, default=dthandler),
                    properties=pika.BasicProperties(
                        content_type="text/plain",
                        delivery_mode=1
                    ),
                    routing_key="")
        session.delete(notification)
        session.commit()
예제 #45
0
 def handle_save(self, action, data):
     session = Session()
     trusted = removeSecurityProxy(self.context)
     sitting = session.query(domain.GroupSitting).get(trusted.sitting_id)
     if sitting.hansard.media_paths is None:
         media_paths = domain.HansardMediaPaths()
         media_paths.web_optimised_video_path = data[
             'web_optimised_video_path']
         media_paths.audio_only_path = data['audio_only_path']
         media_paths.high_quality_video_path = data[
             'high_quality_video_path']
         media_paths.hansard_id = sitting.hansard.hansard_id
         session.add(media_paths)
     else:
         sitting.hansard.media_paths.web_optimised_video_path = data[
             'web_optimised_video_path']
         sitting.hansard.media_paths.audio_only_path = data[
             'audio_only_path']
         sitting.hansard.media_paths.high_quality_video_path = data[
             'high_quality_video_path']
         session.update(sitting)
     session.commit()
     self._next_url = absoluteURL(self.context, self.request) + "/hansard"
     self.request.response.redirect(self._next_url)
예제 #46
0
 def handle_insert(self, action, data):
     self.template_data = []
     session = Session()
     trusted = removeSecurityProxy(ISchedulingContext(self.context))
     if ("rec_type" in data.keys()) and (data["rec_type"] is not None):
         try:
             recurrence_start_date = datetime.datetime \
                     .strptime(data["start_date"], '%Y-%m-%d %H:%M')
         except:
             log.error("The start date of the recurrence  \
                                 is not in the correct format")
         try:
             recurrence_end_date = datetime.datetime.strptime(
                                         data["end_date"], '%Y-%m-%d %H:%M')
         except:
             log.error("The start date of the recurrence is not in \
                                                     the correct format")   
         length = data["event_length"]
         sitting_length = timedelta(seconds=int(length))
         # Check the end date of the recurrence
         # The end date is set to be the end date of the current group 
         # or one year from the present date whichever is sooner.   
            
         group = trusted.get_group()
         # If group is none then there is a big problem
         assert group is not None    
         year = timedelta(days=365)
         now = datetime.datetime.now()                          
         if ((group.end_date is not None) and ((now + year) < group.end_date)) or (group.end_date is None):
             end = now + year 
         else:
             end = group.end_date
         if recurrence_end_date > end:
             recurrence_end_date = end 
         dates = utils.generate_recurrence_dates(recurrence_start_date, 
                                         recurrence_end_date, data["rec_type"])
         for date in dates:
             sitting = domain.GroupSitting()
             sitting.group_id = trusted.group_id
             sitting.start_date = date
             sitting.end_date = date + sitting_length
             sitting.status = None
             if "language" in data.keys():
                 sitting.language = data["language"]
             if "venue" in data.keys():
                 sitting.venue_id = data["venue"]
             # set extra data needed by template
             sitting.ids = data["ids"]
             sitting.action = 'inserted'
             session.add(sitting)
             # commiting after adding a sitting is incredibly inefficient
             # but thats the only way to get the sitting id.
             # Adding recurrring sittings is not a recurrent activity (see,
             # what I did there :)) so we can live with it.
             session.commit(sitting)
             notify(ObjectCreatedEvent(sitting))
             self.template_data.append({"sitting_id": sitting.sitting_id, 
                                        "action": "inserted",
                                        "ids": data["ids"]})
         self.request.response.setHeader('Content-type', 'text/xml')
         return self.template()
     else:
         sitting = domain.GroupSitting()
         try:
             sitting.start_date = datetime.datetime.strptime(
                                         data["start_date"], '%Y-%m-%d %H:%M')
         except:
             log.error("The start date of the sitting \
                                 is not in the correct format")
         try:
             sitting.end_date = datetime.datetime.strptime(data["end_date"], 
                                                             '%Y-%m-%d %H:%M')
         except:
             log.error("The end date of the sitting is not in the correct format")
             
         sitting.group_id = trusted.group_id
         if "language" in data.keys():
             sitting.language = data["language"]
         if "venue" in data.keys():
             sitting.venue_id = data["venue"]
         
         # set extra data needed by template
         sitting.ids = data["ids"]
         sitting.action = 'inserted'
         session.add(sitting)
         session.commit()
         notify(ObjectCreatedEvent(sitting))
         self.template_data.append({"sitting_id": sitting.sitting_id, 
                                    "action": "inserted",
                                    "ids": data["ids"]})
         
         self.request.response.setHeader('Content-type', 'text/xml')
         return self.template()
예제 #47
0
 def handle_post(self, action, data):
     doc = etree.fromstring(data["xml"])
     session = Session()         
     for take in doc.iterchildren('take'):
         sitting_id = take.get("sittingID")
         t_start_time = take.get("startTime").split(":")
         take_start_time = None
          
         if (len(t_start_time) == 3):
             take_start_time = timedelta(hours=int(t_start_time[0]),
                                         minutes=int(t_start_time[1]),
                                         seconds=int(t_start_time[2]))
         if (sitting_id != ""):
             sitting = session.query(domain.GroupSitting).get(int(sitting_id))
         print "Sitting ID",sitting_id, "\n";
         for s in take.iterchildren("speech"):
             s_start_time = s.get("startTime").split(":")
             s_end_time = s.get("endTime").split(":")
             speech_start_time = None
             speech_end_time = None
             if (len(s_start_time) == 3):
                 speech_start_time = timedelta(hours=int(s_start_time[0]),
                                               minutes=int(s_start_time[1]),
                                               seconds=int(s_start_time[2]))
             if (len(s_end_time) == 3):
                 speech_end_time = timedelta(hours=int(s_end_time[0]),
                                             minutes=int(s_end_time[1]),
                                             seconds=int(s_end_time[2]))
             if ( (speech_start_time is not None) and
                  (speech_end_time is not None) and
                  (take_start_time is not None) and
                  (sitting is not None)):
                 speech = domain.Speech() 
                 #hansard_item = domain.HansardItem()
                 speech.start_date =  sitting.start_date+take_start_time + speech_start_time
                 speech.end_date = sitting.start_date+take_start_time + speech_end_time
                 
                 speech.hansard_id = sitting.hansard.hansard_id
                 #import pdb; pdb.set_trace()
                 
                 
                 if s.get("person_id") == "":
                     speech.person_name = s.get("person_name")
                 else:
                     speech.person_id = int(s.get("person_id"))
                 speech.text = s.text
                 session.add(speech)
         for s in take.iterchildren("agenda_item"):
             s_start_time = s.get("startTime").split(":")
             s_end_time = s.get("endTime").split(":")
             agenda_item_start_time = None
             agenda_item_end_time = None
             if (len(s_start_time) == 3):
                 agenda_item_start_time = timedelta(hours=int(s_start_time[0]),
                                               minutes=int(s_start_time[1]),
                                               seconds=int(s_start_time[2]))
             if (len(s_end_time) == 3):
                 agenda_item_end_time = timedelta(hours=int(s_end_time[0]),
                                             minutes=int(s_end_time[1]),
                                             seconds=int(s_end_time[2]))
             if ( (agenda_item_start_time is not None) and
                  (agenda_item_end_time is not None) and
                  (take_start_time is not None) and
                  (sitting is not None)):
                 agenda_item = domain.HansardParliamentaryItem() 
                 #hansard_item = domain.HansardItem()
                 agenda_item.start_date =  sitting.start_date+take_start_time + agenda_item_start_time
                 agenda_item.end_date = sitting.start_date+take_start_time + agenda_item_end_time
                 
                 agenda_item.hansard_id = sitting.hansard.hansard_id
                 agenda_item.parliamentary_item_id = int(s.get("person_id"))
                 session.add(agenda_item)
     session.commit()         
예제 #48
0
 def handle_insert(self, action, data):
     session = Session()
     sitting = domain.GroupSitting()
     trusted = removeSecurityProxy(ISchedulingContext(self.context))
     group = session.query(domain.Group).get(trusted.group_id)
     if ("rec_type" not in data.keys()) or (data["rec_type"] == ""):
         sitting.start_date = datetime.datetime.strptime(
             data["start_date"], '%Y-%m-%d %H:%M')
         sitting.end_date = datetime.datetime.strptime(
             data["end_date"], '%Y-%m-%d %H:%M')
         sitting.group_id = trusted.group_id
         if "language" in data.keys():
             sitting.language = data["language"]
         if "venue" in data.keys():
             sitting.venue_id = data["venue"]
         session.add(sitting)
         notify(ObjectCreatedEvent(sitting))
         session.commit()
         self.request.response.setHeader('Content-type', 'text/xml')
         return '<data><action type="inserted" sid="' + str(
             data["ids"]) + '" tid="' + str(
                 sitting.sitting_id) + '" /></data>'
     else:
         try:
             recurrence_start_date = datetime.datetime.strptime(
                 data["start_date"], '%Y-%m-%d %H:%M')
             recurrence_end_date = datetime.datetime.strptime(
                 data["end_date"], '%Y-%m-%d %H:%M')
         except:
             print "Date is not in the correct format"
         year = timedelta(days=365)
         #max end date is one year from now or end_date of the group whichever is sooner
         if (group is not None) and (group.end_date is not None):
             if (datetime.datetime.now() + year) < group.end_date:
                 end = datetime.datetime.now() + year
             else:
                 end = group.end_date
             if recurrence_end_date > end:
                 recurrence_end_date = end
         else:
             if recurrence_end_date > (datetime.datetime.now() + year):
                 recurrence_end_date = datetime.datetime.now() + year
         recurrence_type = data["rec_type"]
         length = data["event_length"]
         sitting_length = timedelta(seconds=int(length))
         dates = self.generate_recurrence_dates(recurrence_start_date,
                                                recurrence_end_date,
                                                recurrence_type)
         output = '<data>'
         for date in dates:
             sitting = domain.GroupSitting()
             sitting.group_id = trusted.group_id
             sitting.start_date = date
             sitting.end_date = date + sitting_length
             sitting.status = None
             if "language" in data.keys():
                 sitting.language = data["language"]
             if "venue" in data.keys():
                 sitting.venue_id = data["venue"]
             session.add(sitting)
             notify(ObjectCreatedEvent(sitting))
             output = output + '<action type="inserted" sid="' + str(
                 data["ids"]) + '" tid="' + str(sitting.sitting_id) + '" />'
         session.commit()
         output = output + '</data>'
         self.request.response.setHeader('Content-type', 'text/xml')
         return output
예제 #49
0
    def handle_post(self, action, data):
        doc = etree.fromstring(data["xml"])
        session = Session()
        for take in doc.iterchildren('take'):
            sitting_id = take.get("sittingID")
            t_start_time = take.get("startTime").split(":")
            take_start_time = None

            if (len(t_start_time) == 3):
                take_start_time = timedelta(hours=int(t_start_time[0]),
                                            minutes=int(t_start_time[1]),
                                            seconds=int(t_start_time[2]))
            if (sitting_id != ""):
                sitting = session.query(domain.GroupSitting).get(
                    int(sitting_id))
            print "Sitting ID", sitting_id, "\n"
            for s in take.iterchildren("speech"):
                s_start_time = s.get("startTime").split(":")
                s_end_time = s.get("endTime").split(":")
                speech_start_time = None
                speech_end_time = None
                if (len(s_start_time) == 3):
                    speech_start_time = timedelta(hours=int(s_start_time[0]),
                                                  minutes=int(s_start_time[1]),
                                                  seconds=int(s_start_time[2]))
                if (len(s_end_time) == 3):
                    speech_end_time = timedelta(hours=int(s_end_time[0]),
                                                minutes=int(s_end_time[1]),
                                                seconds=int(s_end_time[2]))
                if ((speech_start_time is not None)
                        and (speech_end_time is not None)
                        and (take_start_time is not None)
                        and (sitting is not None)):
                    speech = domain.Speech()
                    #hansard_item = domain.HansardItem()
                    speech.start_date = sitting.start_date + take_start_time + speech_start_time
                    speech.end_date = sitting.start_date + take_start_time + speech_end_time

                    speech.hansard_id = sitting.hansard.hansard_id
                    #import pdb; pdb.set_trace()

                    if s.get("person_id") == "":
                        speech.person_name = s.get("person_name")
                    else:
                        speech.person_id = int(s.get("person_id"))
                    speech.text = s.text
                    session.add(speech)
            for s in take.iterchildren("agenda_item"):
                s_start_time = s.get("startTime").split(":")
                s_end_time = s.get("endTime").split(":")
                agenda_item_start_time = None
                agenda_item_end_time = None
                if (len(s_start_time) == 3):
                    agenda_item_start_time = timedelta(
                        hours=int(s_start_time[0]),
                        minutes=int(s_start_time[1]),
                        seconds=int(s_start_time[2]))
                if (len(s_end_time) == 3):
                    agenda_item_end_time = timedelta(
                        hours=int(s_end_time[0]),
                        minutes=int(s_end_time[1]),
                        seconds=int(s_end_time[2]))
                if ((agenda_item_start_time is not None)
                        and (agenda_item_end_time is not None)
                        and (take_start_time is not None)
                        and (sitting is not None)):
                    agenda_item = domain.HansardParliamentaryItem()
                    #hansard_item = domain.HansardItem()
                    agenda_item.start_date = sitting.start_date + take_start_time + agenda_item_start_time
                    agenda_item.end_date = sitting.start_date + take_start_time + agenda_item_end_time

                    agenda_item.hansard_id = sitting.hansard.hansard_id
                    agenda_item.parliamentary_item_id = int(s.get("person_id"))
                    session.add(agenda_item)
        session.commit()
예제 #50
0
    def handle_insert(self, action, data):
        session = Session()
        self.template_data = []
        trusted = removeSecurityProxy(ISchedulingContext(self.context))
        if ("rec_type" in data.keys()) and (data["rec_type"] is not None):
            # !+ DATETIME(miano, dec-2010) the datetime widget above returns
            # aware datetime objects while the current database setup only
            # supports naive objects. The lines below(and in subsequent actions)
            # convert them to naive datetimes
            recurrence_start_date = data["start_date"].replace(tzinfo=None)
            recurrence_end_date = data["end_date"].replace(tzinfo=None)
            length = data["event_length"]
            sitting_length = timedelta(seconds=int(length))
            #
            # Check the end date of the recurrence
            # The end date is set to be the end date of the current group
            # or one year from the present date whichever is sooner.

            group = trusted.get_group()
            # If group is none then there is a big problem
            assert group is not None
            year = timedelta(days=365)
            now = datetime.datetime.now()
            if ((group.end_date is not None) and
                ((now + year) < group.end_date)) or (group.end_date is None):
                end = now + year
            else:
                end = group.end_date
            if recurrence_end_date > end:
                recurrence_end_date = end
            dates = utils.generate_recurrence_dates(recurrence_start_date,
                                                    recurrence_end_date,
                                                    data["rec_type"])
            recurrent_sittings = []
            for date in dates:
                sitting = domain.GroupSitting()
                sitting.group_id = trusted.group_id
                sitting.start_date = date
                sitting.end_date = date + sitting_length
                sitting.language = data["language"]
                sitting.venue_id = data["venue"]
                session.add(sitting)
                recurrent_sittings.append(sitting)
            session.commit()
            for s in recurrent_sittings:
                notify(ObjectCreatedEvent(s))
                self.template_data.append({
                    "group_sitting_id": s.group_sitting_id,
                    "action": "inserted",
                    "ids": data["ids"]
                })
            self.request.response.setHeader('Content-type', 'text/xml')
            return self.xml_template()
        else:
            sitting = domain.GroupSitting()
            sitting.start_date = data["start_date"].replace(tzinfo=None)
            sitting.end_date = data["end_date"].replace(tzinfo=None)
            sitting.group_id = trusted.group_id
            sitting.language = data["language"]
            sitting.venue_id = data["venue"]
            session.add(sitting)
            session.commit()
            notify(ObjectCreatedEvent(sitting))
            self.template_data.append({
                "group_sitting_id": sitting.group_sitting_id,
                "action": "inserted",
                "ids": data["ids"]
            })
            self.request.response.setHeader('Content-type', 'text/xml')
            return self.xml_template()
예제 #51
0
 def handle_insert(self, action, data):
     session = Session()
     self.template_data = []
     trusted = removeSecurityProxy(ISchedulingContext(self.context))
     if ("rec_type" in data.keys()) and (data["rec_type"] is not None):
         # !+ DATETIME(miano, dec-2010) the datetime widget above returns
         # aware datetime objects while the current database setup only 
         # supports naive objects. The lines below(and in subsequent actions)
         # convert them to naive datetimes
         recurrence_start_date = data["start_date"].replace(tzinfo=None)
         recurrence_end_date = data["end_date"].replace(tzinfo=None)
         length = data["event_length"]
         sitting_length = timedelta(seconds=int(length))
         # 
         # Check the end date of the recurrence
         # The end date is set to be the end date of the current group 
         # or one year from the present date whichever is sooner.   
            
         group = trusted.get_group()
         # If group is none then there is a big problem
         assert group is not None    
         year = timedelta(days=365)
         now = datetime.datetime.now()                          
         if ((group.end_date is not None) and ((now + year) < group.end_date)) or (group.end_date is None):
             end = now + year 
         else:
             end = group.end_date
         if recurrence_end_date > end:
             recurrence_end_date = end 
         dates = utils.generate_recurrence_dates(recurrence_start_date, 
                                         recurrence_end_date, data["rec_type"])
         recurrent_sittings = []
         for date in dates:
             sitting = domain.GroupSitting()
             sitting.group_id = trusted.group_id
             sitting.start_date = date
             sitting.end_date = date + sitting_length
             sitting.language = data["language"]
             sitting.venue_id = data["venue"]
             session.add(sitting)
             recurrent_sittings.append(sitting)
         session.commit()
         for s in recurrent_sittings:    
             notify(ObjectCreatedEvent(s))
             self.template_data.append({"group_sitting_id": s.group_sitting_id, 
                                        "action": "inserted",
                                        "ids": data["ids"]})
         self.request.response.setHeader('Content-type', 'text/xml')
         return self.xml_template()
     else:
         sitting = domain.GroupSitting()
         sitting.start_date = data["start_date"].replace(tzinfo=None)
         sitting.end_date = data["end_date"].replace(tzinfo=None)
         sitting.group_id = trusted.group_id
         sitting.language = data["language"]
         sitting.venue_id = data["venue"]
         session.add(sitting)
         session.commit()
         notify(ObjectCreatedEvent(sitting))
         self.template_data.append({"group_sitting_id": sitting.group_sitting_id, 
                                    "action": "inserted",
                                    "ids": data["ids"]})
         self.request.response.setHeader('Content-type', 'text/xml')
         return self.xml_template()