def get_user_ident_by_id(user_id):
    if user_id:
        url = '%s/api/%s/users/%s' % (USERS_URL, USERS_VERSION, user_id)
        auth_token_cookie = make_superuser_auth_cookie()
        response = requests.get(url, cookies=auth_token_cookie)
        data = response.json()
        return data.get('private_id', None)
    return None
def trigger_arkivverdig_info_processor():
    print "Triggering  the arkivverdig_info processor."
    auth_token_cookie = make_superuser_auth_cookie()
    response = requests.post('%s/api/%s/arkivverdig_info/process' % (SAK_URL, SAK_VERSION),
                             cookies=auth_token_cookie,
                             data=json.dumps([]),
                             headers={'Content-type': 'application/json', 'Accept': 'text/plain'})
    if response.status_code != 201:
        logger.error("Could not trigger the arkivverdig_info processor, response has status %s!\n response=%s"
                     % (response.status_code, response))
def send_notifications_strotimer():
    start_time = datetime.datetime.now() + datetime.timedelta(days=1)    
    end_time = datetime.datetime.now() + datetime.timedelta(days=1, hours=1)      
    data = {
        'start_time': start_time.strftime('%Y-%m-%dT%H:00:00'),
        'end_time': end_time.strftime('%Y-%m-%dT%H:00:00')
    }

    auth_token_cookie = make_superuser_auth_cookie()
    cookies = dict(request.cookies.items() + auth_token_cookie.items())

    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    
    response = requests.post(strotime_notifications_uri, data=json.dumps(data), cookies=cookies, headers=headers)    
    if response.status_code == 201:        
        strotime_slots = json.loads(response.content)
        for strotime_slot in strotime_slots:
            email_address = strotime_slot['email_address']
            resource_name = strotime_slot['resource_name']
            person_name = strotime_slot['person_name']
    
            old_date_format = '%Y-%m-%dT%H:%M:%S'                            
            new_date_format = '%Y-%m-%d %H:%M:%S'                
            start_time = datetime.datetime.strptime(strotime_slot['start_time'], old_date_format)
            start_time = start_time.strftime(new_date_format)
            end_time = datetime.datetime.strptime(strotime_slot['end_time'], old_date_format)
            end_time = end_time.strftime(new_date_format)
            if start_time is not None and \
               end_time is not None and \
               email_address is not None and \
               resource_name is not None and \
               person_name is not None:    
                    logger.info("Email address: " + email_address)
                    logger.info("Resource name: " + resource_name)                        
                    logger.info("Person name: " + person_name)                        
                    logger.info("Start time: " + start_time)                        
                    logger.info("End time: " + end_time)                        

                    message = render_template("email_strotime_notification.txt", 
                                              start_time=start_time, 
                                              end_time=end_time, 
                                              resource_name=resource_name, 
                                              person_name=person_name)                    
                    if message is not None:                        
                        logger.info(message)                        
                        send_email(u'Påminnelse på strøtime',
                                   u'*****@*****.**',
                                   [email_address],
                                   message)
            else:
                logger.error("Missing required data.")
def persist_organisation(data, server_url):
    organisation = data.get('org_number', '-')
    print 'posting:'
    print json.dumps(data)
    headers = {'content-type': 'application/json'}
    r = requests.post(server_url, data=json.dumps(data),
                      cookies=make_superuser_auth_cookie(),
                      headers=headers)

    if r.status_code == 201:
        print 'returned:'
        print r.text
        performed[organisation] = r.json().get('uri')
    else:
        print '!!!!! ***** !!!!!'
        failed[organisation] = "%s:%s" % (r.status_code, json.loads(r.content).get('__error__'))
    def post(self):
        data = request.get_json()

        rammetid_to_application = RammetidToApplication(data.get('umbrella_organisation').get('uri'))
        ensure(POST, rammetid_to_application)

        resource = data.get("resource", None)
        if not resource:
            abort(403, __error__=[u'Ressurs er ikke angitt.'])

        resource = get_resource_for_uri(resource['uri'])
        if not resource:
            abort(404, __error__=[u'Ressursen finnes ikke.'])

        if not resource.repeating_booking_allowed:
            abort(403, __error__=[u'Gjentakende lån ikke tillatt'])

        user = get_user(request.cookies)
        person_uri = '/persons/{}'.format(user['person_id'])
        person = get_person_for_uri(person_uri)
        if not person:
            abort(404, __error__=[u'Personen finnes ikke.'])

        # get umbrella member orgs from organisations backend
        umbrella_member_organisations = get_umbrella_organisation_from_web(data.get('umbrella_organisation').get('uri')).get('organisations', [])

        # get local umbrella organisation object
        umbrella_organisation = get_umbrella_organisation_for_uri(data.get('umbrella_organisation').get('uri'))

        text = "Rammetid fordeling"

        applications = []
        organisations = data.get('organisations', None)
        for organisation in organisations:
            organisation_data = organisations[organisation]
            # have to be superuser if the organisation is not public and not copied to booking already
            organisation = get_organisation_for_uri(organisation_data['uri'], cookies=make_superuser_auth_cookie())

            if not organisation:
                abort(404, __error__=[u'Organisasjonen finnes ikke.'])

            if not any(org.get('uri') == organisation_data['uri'] for org in umbrella_member_organisations):
                abort(403, __error__=[u'Organisasjonen hører ikke til paraplyorganisasjonen'])

            application = Application(person, organisation, text, None, resource)
            application.status = 'Granted'

            slots = organisation_data["slots"]
            for slot_data in slots:

                slot = self.parse_slot(slot_data, application)
                slot_request = self.parse_slot_request(slot_data)

                start_date = slot.start_date
                end_date = slot.end_date
                week_day = slot.week_day
                start_time = slot.start_time
                end_time = slot.end_time

                self.validate_start_and_end_times(start_date, end_date, start_time, end_time)

                if not self.has_matching_rammetid(umbrella_organisation.id, start_date, end_date, week_day, start_time, end_time):
                    abort(400, __error__=[u'Ingen rammetid passer'])

                if self.is_conflict_slot_time(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(400, __error__=[u'Tiden du har søkt på er ikke tilgjengelig'])

                if self.is_conflict_blocked_time(resource, start_date, end_date, week_day, start_time, end_time):
                    abort(400, __error__=[u'Tiden du har søkt på er blokkert'])

                application.request_repeating_slot(slot_request)
                application.add_repeating_slot(slot)
            applications.append(application)

        for application in applications:
            current_app.db_session.add(application)
            current_app.db_session.commit()
            current_app.db_session.refresh(application)

        return applications, 201