<commit_before>#!/usr/bin/env python2.7

from flask import Flask, request
import json, datetime
import sys, os
from string import Template
import xml.etree.ElementTree as ET
import subprocess
import requests
from requests_ntlm import HttpNtlmAuth
from threading import Thread
from Queue import Queue
import argparse

def doWork():
    while True:
        data = q.get()
        response = send_request(data)
        doSomethingWithResult(response)
        q.task_done()

def send_request(data):
    try:
        headers = {}
        headers["Content-type"] = "text/xml; charset=utf-8"
        sys.stderr.write('data='+str(data)+'\n')
        response=requests.post(url,headers = headers, data= data, auth= HttpNtlmAuth(user,password))
        return response
    except:
        return None

def doSomethingWithResult(response):
    if response is None:
        return "KO"
    else:
        tree = ET.fromstring(response.text.encode('utf-8'))

        status = "Free"
        # arrgh, namespaces!!
        elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}BusyType")
        for elem in elems:
            status=elem.text

        tree2=ET.fromstring(response.request.body.encode('utf-8'))
        elems=tree2.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}Address")
        for e in elems:
            room=e.text

        sys.stderr.write(str(datetime.datetime.now().isoformat())+": Status for room: "+str(room)+" => "+status+"\n")
        result.append((status, rooms[room], room))

FILE="available_rooms.json"

app = Flask(__name__)

def is_available(room_email):
    xml_template = open("getavailibility_template.xml", "r").read()
    xml = Template(xml_template)
    headers = {}
    headers["Content-type"] = "text/xml; charset=utf-8"
    data=unicode(xml.substitute(email=room_email,starttime=start_time,endtime=end_time)).strip()
    response=requests.post(url,headers = headers, data= data, auth= HttpNtlmAuth(user,password))
    tree = ET.fromstring(response.text.encode('utf-8'))
    status = "Free"
    # arrgh, namespaces!!
    elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}BusyType")
    for elem in elems:
        status=elem.text
    return (status == "Free")

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        room_name = request.form["room_name"]
        room_email = request.form["room_email"]
        user_email = request.form["user_email"]

        now = datetime.datetime.now().replace(microsecond=0)
        start_time = now.isoformat()
        end_time = (now + datetime.timedelta(hours=2)).isoformat()
        if is_available(room_email):
            book_room(room_name, room_email, user_email, user_email, start_time, end_time)
            return "Room "+str(room_name)+" booked for "+user_email+" from "+str(start_time)+" to "+str(end_time)
        else:
            return "Sorry, room "+str(room_name)+" not available !"
    else:
        return "Error should be a POST"

@app.route('/book', methods=['GET', 'POST'])
def book():
    if request.method == 'POST':
        j = request.get_json()
        sys.stderr.write("Type: "+str(type(j))+"\n")
        sys.stderr.write("j: "+str(j)+"\n")
        sys.stderr.write("user_name: "+str(j["user_name"])+"\n")
        sys.stderr.write("user_email: "+str(j["user_email"])+"\n")
        sys.stderr.write("start_time: "+str(j["starttime"])+"\n")
        sys.stderr.write("end_time: "+str(j["endtime"])+"\n")
        sys.stderr.write("room_name: "+str(j["room_name"])+"\n")

        xml_template = open("resolvenames_template.xml", "r").read()
        xml = Template(xml_template)
        data = unicode(xml.substitute(name=str(j["room_name"])))
        header = "\"content-type: text/xml;charset=utf-8\""
        command = "curl --silent --header " + header +" --data '" + data + "' --ntlm "+ "-u "+ user+":"+password+" "+ url
        #print "command: "+str(command)
        response = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
        #print "response: "+str(response)
        tree = ET.fromstring(response.text.encode('utf-8'))

        elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}Resolution")
        for elem in elems:
            room_email = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress")[0].text
            room_name = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}DisplayName")[0].text

        sys.stderr.write("room_email: "+str(room_email)+"\n")
        if room_email=="":
            return "Sorry, "+str(j["room_name"])+" does not exists !"
        else:
            if is_available(room_email) or not str(j["room_name"]).startswith('ILM-'):
                book_room(str(j["room_name"]), room_email, str(j["user_name"]), str(j["user_email"]), str(j["starttime"]), str(j["endtime"]))
                return "Room "+str(j["room_name"])+" booked for "+str(j["user_name"]+" from "+str(j["starttime"])+" to "+str(j["endtime"]))
            else:
                return "Sorry, room "+str(j["room_name"])+" is busy !"
    else:
        return "Error should be a POST"
   
@app.route('/dispo', methods=['POST'])
def dispo():
    j = request.get_json()
    if "key" not in j:
        return "Sorry, no building where specified !"
    sys.stderr.write("key: "+str(j["key"])+"\n")
    key=str(j["key"])
    if "start" not in j:
        return dispo_building(key)
    start=str(j["start"])
    end=None
    if "end" in j:
        end=str(j["end"])
    return dispo_building(key,start,end)

def findRooms(prefix):
    global rooms

    rooms={}
    xml_template = open("resolvenames_template.xml", "r").read()
    xml = Template(xml_template)

    data = unicode(xml.substitute(name=prefix))

    header = "\"content-type: text/xml;charset=utf-8\""
    #command = "curl --silent --header " + header +" --data '" + data + "' --ntlm "+"--negotiate "+ "-u "+ user+":"+password+" "+ url
    command = "curl --silent --header " + header +" --data '" + data + "' --ntlm "+ "-u "+ user+":"+password+" "+ url
    #print "command: "+str(command)
    response = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
    #print "response: "+str(response)
    tree = ET.fromstring(response.text.encode('utf-8'))

    elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}Resolution")
    for elem in elems:
        email = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress")
        name = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}DisplayName")
        if len(email) > 0 and len(name) > 0 and name[0].text.startswith(prefix):
            rooms[email[0].text] = name[0].text
    return rooms        


def dispo_building(b,start=None, end=None):
    global result
    result=list()
    now = datetime.datetime.now().replace(microsecond=0)
    if start is None:
        start = now
    if end is None:
        end = (start + datetime.timedelta(hours=2))

    findRooms(b)
    sys.stderr.write("List of rooms: "+str(rooms)+"\n")
<commit_msg>fix datetime format issue<commit_after>#!/usr/bin/env python2.7

from flask import Flask, request
import json, datetime
import sys, os
from string import Template
import xml.etree.ElementTree as ET
import subprocess
import requests
from requests_ntlm import HttpNtlmAuth
from threading import Thread
from Queue import Queue
import argparse

def doWork():
    while True:
        data = q.get()
        response = send_request(data)
        doSomethingWithResult(response)
        q.task_done()

def send_request(data):
    try:
        headers = {}
        headers["Content-type"] = "text/xml; charset=utf-8"
        sys.stderr.write('data='+str(data)+'\n')
        response=requests.post(url,headers = headers, data= data, auth= HttpNtlmAuth(user,password))
        return response
    except:
        return None

def doSomethingWithResult(response):
    if response is None:
        return "KO"
    else:
        tree = ET.fromstring(response.text.encode('utf-8'))

        status = "Free"
        # arrgh, namespaces!!
        elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}BusyType")
        for elem in elems:
            status=elem.text

        tree2=ET.fromstring(response.request.body.encode('utf-8'))
        elems=tree2.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}Address")
        for e in elems:
            room=e.text

        sys.stderr.write(str(datetime.datetime.now().isoformat())+": Status for room: "+str(room)+" => "+status+"\n")
        result.append((status, rooms[room], room))

FILE="available_rooms.json"

app = Flask(__name__)

def is_available(room_email):
    xml_template = open("getavailibility_template.xml", "r").read()
    xml = Template(xml_template)
    headers = {}
    headers["Content-type"] = "text/xml; charset=utf-8"
    data=unicode(xml.substitute(email=room_email,starttime=start_time,endtime=end_time)).strip()
    response=requests.post(url,headers = headers, data= data, auth= HttpNtlmAuth(user,password))
    tree = ET.fromstring(response.text.encode('utf-8'))
    status = "Free"
    # arrgh, namespaces!!
    elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}BusyType")
    for elem in elems:
        status=elem.text
    return (status == "Free")

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        room_name = request.form["room_name"]
        room_email = request.form["room_email"]
        user_email = request.form["user_email"]

        now = datetime.datetime.now().replace(microsecond=0)
        start_time = now.isoformat()
        end_time = (now + datetime.timedelta(hours=2)).isoformat()
        if is_available(room_email):
            book_room(room_name, room_email, user_email, user_email, start_time, end_time)
            return "Room "+str(room_name)+" booked for "+user_email+" from "+str(start_time)+" to "+str(end_time)
        else:
            return "Sorry, room "+str(room_name)+" not available !"
    else:
        return "Error should be a POST"

@app.route('/book', methods=['GET', 'POST'])
def book():
    if request.method == 'POST':
        j = request.get_json()
        sys.stderr.write("Type: "+str(type(j))+"\n")
        sys.stderr.write("j: "+str(j)+"\n")
        sys.stderr.write("user_name: "+str(j["user_name"])+"\n")
        sys.stderr.write("user_email: "+str(j["user_email"])+"\n")
        sys.stderr.write("start_time: "+str(j["starttime"])+"\n")
        sys.stderr.write("end_time: "+str(j["endtime"])+"\n")
        sys.stderr.write("room_name: "+str(j["room_name"])+"\n")

        xml_template = open("resolvenames_template.xml", "r").read()
        xml = Template(xml_template)
        data = unicode(xml.substitute(name=str(j["room_name"])))
        header = "\"content-type: text/xml;charset=utf-8\""
        command = "curl --silent --header " + header +" --data '" + data + "' --ntlm "+ "-u "+ user+":"+password+" "+ url
        #print "command: "+str(command)
        response = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
        #print "response: "+str(response)
        tree = ET.fromstring(response.text.encode('utf-8'))

        elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}Resolution")
        for elem in elems:
            room_email = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress")[0].text
            room_name = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}DisplayName")[0].text

        sys.stderr.write("room_email: "+str(room_email)+"\n")
        if room_email=="":
            return "Sorry, "+str(j["room_name"])+" does not exists !"
        else:
            if is_available(room_email) or not str(j["room_name"]).startswith('ILM-'):
                book_room(str(j["room_name"]), room_email, str(j["user_name"]), str(j["user_email"]), str(j["starttime"]), str(j["endtime"]))
                return "Room "+str(j["room_name"])+" booked for "+str(j["user_name"]+" from "+str(j["starttime"])+" to "+str(j["endtime"]))
            else:
                return "Sorry, room "+str(j["room_name"])+" is busy !"
    else:
        return "Error should be a POST"
   
@app.route('/dispo', methods=['POST'])
def dispo():
    j = request.get_json()
    if "key" not in j:
        return "Sorry, no building where specified !"
    sys.stderr.write("key: "+str(j["key"])+"\n")
    key=str(j["key"])
    if "start" not in j:
        return dispo_building(key)
    start=str(j["start"])
    end=None
    if "end" in j:
        end=str(j["end"])
    return dispo_building(key,start,end)

def findRooms(prefix):
    global rooms

    rooms={}
    xml_template = open("resolvenames_template.xml", "r").read()
    xml = Template(xml_template)

    data = unicode(xml.substitute(name=prefix))

    header = "\"content-type: text/xml;charset=utf-8\""
    #command = "curl --silent --header " + header +" --data '" + data + "' --ntlm "+"--negotiate "+ "-u "+ user+":"+password+" "+ url
    command = "curl --silent --header " + header +" --data '" + data + "' --ntlm "+ "-u "+ user+":"+password+" "+ url
    #print "command: "+str(command)
    response = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
    #print "response: "+str(response)
    tree = ET.fromstring(response.encode('utf-8'))

    elems=tree.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}Resolution")
    for elem in elems:
        email = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}EmailAddress")
        name = elem.findall(".//{http://schemas.microsoft.com/exchange/services/2006/types}DisplayName")
        if len(email) > 0 and len(name) > 0 and name[0].text.startswith(prefix):
            rooms[email[0].text] = name[0].text
    return rooms        


def dispo_building(b,start=None, end=None):
    global result
    result=list()
    now = datetime.datetime.now().replace(microsecond=0)
    if start is None:
        start = now
    if end is None:
        end = (start + datetime.timedelta(hours=2))

    findRooms(b)
    sys.stderr.write("List of rooms: "+str(rooms)+"\n")

{'fraction_non_alphanumeric': 0.17498788172564228, 'fraction_numerical': 0.008586662973478291, 'mean_word_length': 3.1800289435600577, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 40}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3823271', 'n_tokens_mistral': 4840, 'n_tokens_neox': 4627, 'n_words': 881}