예제 #1
0
    def get_space_usage(self,args):

        print("In get_space_usage")

        headers = {
            'Authorization': 'Bearer ' + str(self.dropbox_access_token),
        }

        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/users/get_space_usage', headers=headers)

        # Response check
        if r.status_code == requests.codes.ok:

            # Fetching response in JSON
            response = r.content.decode("utf-8")
            response = json.loads(response)
            print(response)

            #Creating a message object from YA SDK
            message = MessageClass()
            message.message_text = "Space usage/allocation details :"

            attachment = MessageAttachmentsClass()

            used_gb = float(response['used']/1000000000)
            allocated_gb = float(response['allocation']['allocated']/1000000000)



            field1 = AttachmentFieldsClass()
            field1.title = "Used : "
            field1.value = str(Decimal(str(used_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb"
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Allocated : "
            field2.value = str(Decimal(str(allocated_gb)).quantize(Decimal('.01'), rounding=ROUND_DOWN)) + " gb"
            attachment.attach_field(field2)

            message.attach(attachment)
            return message.to_json()


        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #2
0
    def get_account_info(self,args):

        print("In get_company_info")
        endpoint = "https://api.dropboxapi.com/2/users/get_account"

        # API parameteres for getting account information

        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        data = {"account_id": str(self.account_id)}

        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/users/get_account', headers=headers, json=data)

        # Response check
        if r.status_code == requests.codes.ok:

            # Getting response in JSON
            response = r.content.decode("utf-8")
            response = json.loads(response)

            # Creating message objects to structure the message to be shown
            message = MessageClass()
            message.message_text = "User Account Details :"

            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "Name :"
            field1.value = response["name"]["display_name"]
            attachment.attach_field(field1)


            field2 = AttachmentFieldsClass()
            field2.title = "E-mail :"
            field2.value = response["email"]
            attachment.attach_field(field2)
            attachment.image_url = response["profile_photo_url"]

            message.attach(attachment)
            return message.to_json()
        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #3
0
    def get_all_shared_folders(self,args):

        print("In get_all_shared_folders")

        endpoint = "https://api.dropboxapi.com/2/sharing/list_folders"
        headers = {
            'Authorization': 'Bearer ' + str(self.dropbox_access_token),
            'Content-Type': 'application/json',
        }

        data = {"limit": 100,"actions": []}

        # Consuming the API
        r = requests.post(endpoint, headers=headers, json=data)

        # Response check
        if (r.status_code == requests.codes.ok):
            response = r.content.decode("utf-8")
            response = json.loads(response)
            print(response)

            #Creating message from YA SDK
            message = MessageClass()
            message.message_text = "All shared file details :"

            attachment = MessageAttachmentsClass()

            for i in range(0,len(response['entries'])):
                field1 = AttachmentFieldsClass()
                field1.title = "Name :"
                field1.value = response['entries'][i]['name']
                attachment.attach_field(field1)

                field2 = AttachmentFieldsClass()
                field2.title = "Preview URL :"
                field2.value = response['entries'][i]['preview_url']
                attachment.attach_field(field2)

            message.attach(attachment)
            return message.to_json()
        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #4
0
    def download_file(self,args):
        print("In download_file")
        # Fetching the arguments passed from slack
        path = args['path']

        # API call parameters for creating a customer

        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        data = {"path": path}

        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/files/get_temporary_link', headers=headers, json=data)

        # Response check
        if (r.status_code == requests.codes.ok):

            # Getting the response
            response = r.content.decode("utf-8")
            response = json.loads(response)
            print(response)

            # Creating message using YA SDK
            message = MessageClass()
            message.message_text = "Temporary link to download :"
            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "This link expires in 4 Hr :"
            field1.value = response['link']
            attachment.attach_field(field1)

            message.attach(attachment)
            return message.to_json()
        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #5
0
    def get_all_file_requests(self,args):

        print("In get_all_file_requests")

        # API call parameters for creating an invoice
        headers = {
            'Authorization': 'Bearer ' + str(self.dropbox_access_token),
        }

        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/file_requests/list', headers=headers)

        # Response check
        if r.status_code == requests.codes.ok:
            response = r.content.decode("utf-8")
            response = json.loads(response)
            print(response)

            # Creating message from YA SDK
            message = MessageClass()
            attachment = MessageAttachmentsClass()

            if len(response) == 0:
                message.message_text = "No File Requests"
                message.attach(attachment)
                return message.to_json()
            else:
                message.message_text = "All file requests :"
                message.attach(attachment)
                return message.to_json()

        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #6
0
파일: views.py 프로젝트: vimalvk9/dropbox
def webhook(request, hash_str=""):

    '''Respond to the webhook verification (GET request) by echoing back the challenge parameter.'''
    print("Inside webhook")

    if request.method == "GET":
        print("Inside webhook validation")
        challenge = request.GET.get('challenge',None)

        if challenge != None:
            return HttpResponse(challenge,status=200)
        else:
            return HttpResponse(status=400)

    else:
        print("In notifications")
        webhook_id = hash_str
        data =  (request.body.decode('utf-8'))
        response_json = json.loads(data)
        print(response_json)

        data = {
	            "users": [],
	            "accounts": []
            }

        try:
            yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id)
            print(yellow_obj)
            access_token = yellow_obj.yellowant_token
            print(access_token)
            integration_id = yellow_obj.yellowant_integration_id
            service_application = str(integration_id)
            print(service_application)

            # Creating message object for webhook message

            webhook_message = MessageClass()
            webhook_message.message_text = "File/Folder updated !"
            attachment = MessageAttachmentsClass()
            attachment.title = "Updated file/folder details :"

            for i in range(0,len(response_json['list_folder']['accounts'])):
                field1 = AttachmentFieldsClass()
                field1.title = "Id : "
                field1.value = response_json['list_folder']['accounts'][i]
                data["accounts"].append(response_json['list_folder']['accounts'][i])
                attachment.attach_field(field1)

            attachment2 = MessageAttachmentsClass()
            attachment2.title = "User update details :"

            for i in range(0, len(response_json['delta']['users'])):
                field2 = AttachmentFieldsClass()
                field2.title = "Id : "
                field2.value = response_json['delta']['users'][i]
                data["users"].append(response_json['delta']['users'][i])
                attachment2.attach_field(field2)

            button = MessageButtonsClass()
            button.name = "1"
            button.value = "1"
            button.text = "Get all files and folders "
            button.command = {
                "service_application": service_application,
                "function_name": 'get_all_folders',
                "data" : {"path": "",
                "recursive": True,
                "include_media_info": False,
                "include_deleted": False,
                "include_has_explicit_shared_members": False,
                "include_mounted_folders": True}
                }

            attachment.attach_button(button)
            webhook_message.attach(attachment)
            webhook_message.attach(attachment2)
            #print(integration_id)
            print("-----------")
            print(data)
            print("------------")
            webhook_message.data = data
            # Creating yellowant object
            yellowant_user_integration_object = YellowAnt(access_token=access_token)

            # Sending webhook message to user
            send_message = yellowant_user_integration_object.create_webhook_message(
                requester_application=integration_id,
                webhook_name="files_folders_update", **webhook_message.get_dict())

            return HttpResponse("OK", status=200)

        except YellowUserToken.DoesNotExist:
            return HttpResponse("Not Authorized", status=403)
예제 #7
0
def startGameAgainstPlayer(args,user_integration):
    """

    """


    player_object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)

    opponent_object = UserIntegration.objects.get(yellowant_integration_id=player_object.opponent_integration_id)

    board = chess.Board(player_object.board_state)
    color = args['Color']

    attachment = MessageAttachmentsClass()

    print(color + " to move")

    if (color=="Black"):
        webhook_message = MessageClass()
        webhook_message.message_text = "You are playing White!"
        attachment = MessageAttachmentsClass()
        button = MessageButtonsClass()
        button.text = "Make Move"
        button.value = "Make Move"
        button.name = "Make Move"
        button.command = {
            "service_application": str(opponent_object.yellowant_integration_id),
            "function_name": "makemoveagainst",
            "data": {"user_int": player_object.yellowant_integration_id},
        }
        attachment.attach_button(button)

        webhook_message.attach(attachment)
        access_token = opponent_object.yellowant_integration_token
        yellowant_user_integration_object = YellowAnt(access_token=access_token)

        send_message = yellowant_user_integration_object.create_webhook_message(
            requester_application=opponent_object.yellowant_integration_id,
            webhook_name="webhook", **webhook_message.get_dict())

        return

    else:
        print("Inside else")
        m = MessageClass()
        attachment = MessageAttachmentsClass()
        attachment.image_url = IMAGE_URL + INITIAL_BOARD
        m.message_text = "Make a Move"
        field1 = AttachmentFieldsClass()
        field1.title = "Move"
        field1.value = color + " to move"
        attachment.attach_field(field1)

        attachment.image_url = IMAGE_URL + INITIAL_BOARD


        button = MessageButtonsClass()
        button.text = "Make Move"
        button.value = "Make Move"
        button.name = "Make Move"
        button.command = {
            "service_application": str(player_object.yellowant_integration_id),
            "function_name": "makemoveagainst",
            "inputs": ["move"],
            "data": {"user_int": player_object.yellowant_integration_id},
        }
        attachment.attach_button(button)

        m.attach(attachment)

        return m
예제 #8
0
def playComputer(args,user_integration):
    """
    Function to play against the Computer.
    """
    object = UserIntegration.objects.get(yellowant_integration_id=user_integration.yellowant_integration_id)
    board = chess.Board(object.board_state)
    dir_path = os.path.dirname(os.path.realpath(__file__))
    print(dir_path)
    engine = chess.uci.popen_engine("/app/stockfish/Linux/stockfish-9")
    #engine = chess.uci.popen_engine("/app/Stockfish-master/src/stockfish")
    col = color(object.board_state[-12])
    engine.position(board)
    move = engine.go(movetime=2000)
    board.push(chess.Move.from_uci(str(move[0])))
    m = MessageClass()
    if board.is_insufficient_material():
        print("Insufficient material")
        m.message_text = "Insufficient material"

        return m

    if board.is_stalemate():
        print("Stalemate")
        m.message_text = "Stalemate"


    if board.is_checkmate():
        print("Computer wins")
        m.message_text = "Checkmate !! \n"+col + " wins"

        return m

    object.board_state = board.fen()
    object.save()

    attachment = MessageAttachmentsClass()
    print(IMAGE_URL + board.fen()[:-13])
    attachment.image_url = IMAGE_URL + board.fen()[:-13]

    button = MessageButtonsClass()
    button.text = "Make move"
    button.value = "Make move"
    button.name = "Make move"
    button.command = {"service_application": str(user_integration.yellowant_integration_id), "function_name": "makemove",\
                      "inputs": ["move"],
                      "data" : {"move":"testing"}
                      }
    attachment.attach_button(button)

    button1 = MessageButtonsClass()
    button1.text = "Play Computer"
    button1.value = "Play Computer"
    button1.name = "Play Computer"
    button1.command = {"service_application": str(user_integration.yellowant_integration_id), "function_name": "playcomputer", \
                       "data": {"move": "testing"}
                      }
    attachment.attach_button(button1)

    button2 = MessageButtonsClass()
    button2.text = "Accept Invitation"
    button2.value = "Accept Invitation"
    button2.name = "Accept Invitation"
    button2.command = {
                      "service_application" : str(user_integration.yellowant_integration_id),
                      "function_name" : "accept",
                      "data" : {"user_int": user_integration.yellowant_integration_id }
                     }
    attachment.attach_button(button2)


    m.attach(attachment)

    return m
예제 #9
0
def get_incident(args, user_integration):

    access_token_object = Servicenow_model.objects.get(
        user_integration=user_integration.id)
    access_token = access_token_object.access_token
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + access_token
    }

    sys_id = args.get('sys_id')
    instance = access_token_object.instance
    url = " https://" + instance + ".service-now.com/api/now/table/incident/" + sys_id

    response = requests.get(url=url, headers=headers)

    message = MessageClass()
    message.message_text = "The incident is"

    attachment = MessageAttachmentsClass()

    field1 = AttachmentFieldsClass()
    field1.title = "Incident Name"
    field1.value = response.json()["result"]["number"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Created by"
    field1.value = response.json()["result"]["sys_created_by"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Incident State"
    field1.value = response.json()["result"]["incident_state"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Description"
    field1.value = response.json()["result"]["description"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Priority"
    field1.value = response.json()["result"]["priority"]
    attachment.attach_field(field1)

    field1 = AttachmentFieldsClass()
    field1.title = "Impact"
    field1.value = response.json()["result"]["impact"]
    attachment.attach_field(field1)

    button = MessageButtonsClass()
    button.text = "Modify State"
    button.value = "Modify State"
    button.name = "Modify State"
    button.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "modifystate",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["state"]
    }
    attachment.attach_button(button)

    button = MessageButtonsClass()
    button.text = "Change impact"
    button.value = "Change impact"
    button.name = "Change impact"
    button.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "changeimpact",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["impact"]
    }
    attachment.attach_button(button)

    button1 = MessageButtonsClass()
    button1.text = "Close Incident"
    button1.value = "Close Incident"
    button1.name = "Close Incident"
    button1.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "closeincident",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["close_notes", "close_code"]
    }
    attachment.attach_button(button1)

    button2 = MessageButtonsClass()
    button2.text = "Resolve Incident"
    button2.value = "Resolve Incident"
    button2.name = "Resolve Incident"
    button2.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "resolveincident",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["resolve_notes", "close_code"]
    }
    attachment.attach_button(button2)

    button3 = MessageButtonsClass()
    button3.text = "Change priority"
    button3.value = "Change priority"
    button3.name = "Change priority"
    button3.command = {
        "service_application": str(user_integration.yellowant_integration_id),
        "function_name": "changepriority",
        "data": {
            "sys_id": sys_id
        },
        "inputs": ["priority"]
    }
    attachment.attach_button(button3)

    message.attach(attachment)

    return message
예제 #10
0
파일: views.py 프로젝트: vimalvk9/mailgun
def webhook_unsubscribed(request, webhook_id):
    print("In webhook_unsubscribed")
    """
    Webhook function to notify user about update in unsbscribes
    """

    urllib.parse.unquote(request.body.decode("utf-8"))
    params_dict = urllib.parse.parse_qsl(request.body)
    params = dict(params_dict)

    ## Extracting necessary data

    device_type = params[b'device-type'].decode("utf-8")
    name = params[b'client-name'].decode("utf-8")
    domain = params[b'domain'].decode("utf-8")
    city = params[b'city'].decode('utf-8')
    country = params[b'country'].decode('utf-8')
    recipient = params[b'recipient'].decode('utf-8')

    try:

        # Fetching yellowant object
        yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id)
        print(yellow_obj)
        access_token = yellow_obj.yellowant_token
        print(access_token)
        integration_id = yellow_obj.yellowant_integration_id
        service_application = str(integration_id)
        print(service_application)

        # Creating message object for webhook message

        webhook_message = MessageClass()
        webhook_message.message_text = "Unsubscribe details"

        attachment_message = MessageAttachmentsClass()

        field2 = AttachmentFieldsClass()
        field2.title = "Email Id :"
        field2.value = recipient
        attachment_message.attach_field(field2)

        field1 = AttachmentFieldsClass()
        field1.title = "Browser :"
        field1.value = name
        attachment_message.attach_field(field1)

        field3 = AttachmentFieldsClass()
        field3.title = "Domain"
        field3.value = domain
        attachment_message.attach_field(field3)

        field4 = AttachmentFieldsClass()
        field4.title = "Device type"
        field4.value = device_type
        attachment_message.attach_field(field4)

        field5 = AttachmentFieldsClass()
        field5.title = "City"
        field5.value = city
        attachment_message.attach_field(field5)

        field6 = AttachmentFieldsClass()
        field6.title = "Country"
        field6.value = country
        attachment_message.attach_field(field6)

        webhook_message.attach(attachment_message)

        attachment = MessageAttachmentsClass()
        attachment.title = "Unsubscribe operations"

        button_get_incidents = MessageButtonsClass()
        button_get_incidents.name = "1"
        button_get_incidents.value = "1"
        button_get_incidents.text = "Get unsubscribe details"
        button_get_incidents.command = {
            "service_application": service_application,
            "function_name": 'get_unsubscribes',
            "data": {}
        }

        attachment.attach_button(button_get_incidents)
        webhook_message.data = {
            "recipient_email_id": recipient,
            "domain": domain,
            "device_type": device_type,
            "city": city,
            "country": country,
            "name": name,
        }
        webhook_message.attach(attachment)
        #print(integration_id)

        # Creating yellowant object
        yellowant_user_integration_object = YellowAnt(
            access_token=access_token)

        # Sending webhook message to user
        send_message = yellowant_user_integration_object.create_webhook_message(
            requester_application=integration_id,
            webhook_name="notify_unsubscribe",
            **webhook_message.get_dict())
        return HttpResponse("OK", status=200)

    except YellowUserToken.DoesNotExist:
        return HttpResponse("Not Authorized", status=403)
예제 #11
0
    def get_more_folders(self,args):

        print("In 	get_more_folders")

        # Fetching arguments passed from Slack
        cursor = args['cursor']

        # API call parameters for getting customer details
        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        data = {"cursor": cursor}
        re = requests.post('https://api.dropboxapi.com/2/files/list_folder/continue', headers=headers,
                           json=data)

        if re.status_code == requests.codes.ok:

            res = re.content.decode("utf-8")
            res = json.loads(res)
            print("----")
            print(res)

            message = MessageClass()

            message.message_text = "More files and folders :"
            attachment = MessageAttachmentsClass()

            for i in range(0, len(res['entries'])):

                field1 = AttachmentFieldsClass()
                field1.title = "Name :"
                field1.value = res['entries'][i]['name']
                attachment.attach_field(field1)

                field2 = AttachmentFieldsClass()
                field2.title = "Type :"
                field2.value = res['entries'][i]['.tag']
                attachment.attach_field(field2)

            attachment2 = MessageAttachmentsClass()

            if res['has_more'] == True:
                button = MessageButtonsClass()
                button.name = "1"
                button.value = "1"
                button.text = "Get more files and folders"
                button.command = {
                    "service_application": str(self.user_integration.yellowant_integration_id),
                    "function_name": 'get_more_folders',
                    "data": {"cursor": res['cursor']}
                }
                attachment2.attach_button(button)
                message.attach(attachment)
                message.attach(attachment2)
                return message.to_json()

            message.attach(attachment)
            return message.to_json()
        else:
            m = MessageClass()
            print(re.content.decode("utf-8"))
            d = re.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(re.status_code, re.text)
            return m.to_json()
예제 #12
0
    def get_shared_links(self,args):

        print("In get_shared_links")

        flag = False
        # Arguments passed from slack
        # For the optional argument
        try:
            path = args['path']
            flag = True
        except:
            flag = False

        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }


        endpoint = 'https://api.dropboxapi.com/2/sharing/list_shared_links'

        if flag == True:
            data = {"path": path}
        else:
            data = {}

        # Consuming the API
        r = requests.post(endpoint, headers=headers, json=data)

        # Response check
        if r.status_code == requests.codes.ok:

            # Getting response in JSON
            response = r.content.decode("utf-8")
            response = json.loads(response)
            print(response)
            links = response['links']

            message = MessageClass()
            message.message_text = "List of all shared links :"
            attachment = MessageAttachmentsClass()

            for i in range(0,len(links)):
                try:
                    field1 = AttachmentFieldsClass()
                    field1.title = "Name :"
                    field1.value = links[i]['name']
                    attachment.attach_field(field1)
                except KeyError : 'name'

                # field2 = AttachmentFieldsClass()
                # field2.title = "Type :"
                # field2.value = links[i]['.tag']
                # attachment.attach_field(field2)

                field3 = AttachmentFieldsClass()
                field3.title = "Preview URL :"
                field3.value = links[i]['url']
                attachment.attach_field(field3)

            message.attach(attachment)
            return message.to_json()
        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #13
0
def search_invoice(
    args, user_integration
):  #Search by contact name(company) or invoice number or due date
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)
    string = args['Search-key']
    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }

    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    xero = Xero(new_credentials)
    #print("The invoices found are")
    s = xero.invoices.all()
    x = ''
    print("The invoices that match are:")
    for i in s:
        date = str(i['DueDateString'])
        if i['Contact']['Name'].find(string) != -1 or i['InvoiceNumber'].find(
                string) != -1 or date.find(string) != -1:
            print("Invoice Number:", i['InvoiceNumber'], "Reference: ",
                  i['Reference'], "Payments: ", i['Payments'],
                  "\nCredit Notes", i['CreditNotes'])
            print("Amount Due: ", i['AmountDue'], "Amount Paid: ",
                  i['AmountPaid'], "Amount Credited ", i['AmountCredited'],
                  "\nCurrency Rate: ", i['CurrencyRate'],
                  "\nContact Details:\n Name:", i['Contact']['Name'],
                  "Address:", i['Contact']['Addresses'], "Phone No: ",
                  i['Contact']['Phones'])
            print("Subtotal:", i['SubTotal'], "Total Tax:", i['TotalTax'],
                  "Total: ", i['Total'])

            print(date)
            print("Due Date:", date)
            x += "Invoice Number: " + str(
                i['InvoiceNumber']) + " Reference: " + str(
                    i['Reference']) + " Payments: " + str(
                        i['Payments']) + "\nCredit Notes " + str(
                            i['CreditNotes'])
            x += " Amount Due: " + str(
                i['AmountDue']) + " Amount Paid: " + str(
                    i['AmountPaid']) + " Amount Credited " + str(
                        i['AmountCredited'])
            x += "\nCurrency Rate: " + str(
                i['CurrencyRate']) + "\nContact Details:\n Name: " + str(
                    i['Contact']['Name']) + " Address:" + str(
                        i['Contact']['Addresses']) + " Phone No: " + str(
                            i['Contact']['Phones'])
            x += " Subtotal: " + str(i['SubTotal']) + " Total Tax: " + str(
                i['TotalTax']) + " Total: " + str(i['Total']) + "\n\n"
    if x == '':
        x = "Nothing Found matching your query"
    m = MessageClass()
    attachment = MessageAttachmentsClass()
    field = AttachmentFieldsClass()
    field.title = "The Invoices retrieved are:"
    field.value = x
    attachment.attach_field(field)
    m.attach(attachment)
    return m
예제 #14
0
def list_contacts(args, user_integration):
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }

    print(saved_state)

    #xero = Xero(credentials)

    #state=xcr.XERO_STATE
    #state=ast.literal_eval(state[0])
    print("HELLO")
    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    #print(new_credentials.state)
    #print(xero.contacts.all())
    x = ''
    s = xero.contacts.all()
    for i in s:
        #print(i)
        print(
            "CompanyName: " + i['Name'] + "\nFirst Name: " + i['FirstName'],
            " Last Name:",
            i['LastName'] + " \nEmail Address: " + i['EmailAddress'] +
            "  \nStreet Address: " + i['Addresses'][1]['AddressLine1'] + ", " +
            i['Addresses'][1]['AddressLine2'] + ", " +
            i['Addresses'][1]['AddressLine3'] + "\n," +
            i['Addresses'][1]['City'] + ", " + i['Addresses'][1]['Region'] +
            ", " + i['Addresses'][1]['Country'],
            i['Addresses'][1]['PostalCode'] + "\nPhone: " +
            i['Phones'][1]['PhoneCountryCode'], i['Phones'][1]['PhoneNumber'],
            i['Phones'][3]['PhoneCountryCode'], i['Phones'][3]['PhoneNumber'] +
            "\n" + "Contact ID: " + i['ContactID'] + "\n")
        x = x + "CompanyName: " + str(i['Name']) + "\nFirst Name: " + str(
            i['FirstName']) + " Last Name:"
        x += i['LastName'] + " \nEmail Address: " + i[
            'EmailAddress'] + "  \nStreet Address: "
        x += i['Addresses'][1]['AddressLine1'] + ", " + i['Addresses'][1][
            'AddressLine2'] + ", " + i['Addresses'][1][
                'AddressLine3'] + "," + i['Addresses'][1]['City'] + ", " + i[
                    'Addresses'][1]['Region'] + ", "
        x += "\nPhone No:" + i['Phones'][1]['PhoneCountryCode'] + " " + i[
            'Phones'][1]['PhoneNumber'] + "\n" + i['Phones'][3][
                'PhoneCountryCode'] + " "
        x += i['Phones'][3]['PhoneNumber'] + "\n" + "Contact ID: " + i[
            'ContactID'] + "\n"

    m = MessageClass()
    field = AttachmentFieldsClass()
    field.title = "Your list of contacts:"
    field.value = x
    attachment = MessageAttachmentsClass()
    attachment.attach_field(field)
    m.attach(attachment)
    return m
예제 #15
0
def list_invoices(args, user_integration):
    print("LIST INVOICES")
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }
    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    print("The invoices present are:")
    print(xero.invoices.all())
    s = xero.invoices.all()
    x = ''
    for i in s:
        print("Invoice Number:", i['InvoiceNumber'], "Reference: ",
              i['Reference'], "Payments: ", i['Payments'], "\nCredit Notes",
              i['CreditNotes'])
        print("Amount Due: ", i['AmountDue'], "Amount Paid: ", i['AmountPaid'],
              "Amount Credited ", i['AmountCredited'], "\nCurrency Rate: ",
              i['CurrencyRate'], "\nContact Details:\n Name:",
              i['Contact']['Name'], "Address:", i['Contact']['Addresses'],
              "Phone No: ", i['Contact']['Phones'])
        print("Subtotal:", i['SubTotal'], "Total Tax:", i['TotalTax'],
              "Total: ", i['Total'])
        date = str(i['DueDateString'])
        print(date)
        print("Due Date:", date)
        x += "Invoice Number: " + i['InvoiceNumber'] + " Reference: " + i[
            'Reference']
        x += " Payments: " + str(i['Payments']) + "\nCredit Notes" + str(
            i['CreditNotes'])
        x += "Amount Due: " + str(i['AmountDue']) + " Amount Paid: " + str(
            i['AmountPaid']) + " Amount Credited " + str(
                i['AmountCredited']) + "\nCurrency Rate: " + str(
                    i['CurrencyRate']) + "\nContact Details:\n Name:"
        x += i['Contact']['Name'] + " Address: " + str(
            i['Contact']['Addresses']) + " Phone No: " + str(
                i['Contact']['Phones'])
        x += "Subtotal: " + str(i['SubTotal']) + " Total Tax:" + str(
            i['TotalTax']) + " Total: " + str(i['Total'])
        x += "\nDue Date: " + date + "\n\n"
    m = MessageClass()
    field = AttachmentFieldsClass()
    field.title = "Your invoices are:"
    field.value = x
    attachment = MessageAttachmentsClass()
    attachment.attach_field(field)

    m.attach(attachment)
    return m
예제 #16
0
def update_contact(args, user_integration):
    #contact_id='u\''+contact_id+'\''
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }

    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    #email ID compulsory
    name = ''
    address_line1 = ''
    mobile = ''
    address_line2 = ''

    s = xero.contacts.all()
    print("UPDATE CONTACT")
    if args.get("Name", None) is not None:
        name = args['Name']
    email = args['EmailID']
    if args.get('Mobile-Number', None) is not None:
        mobile = args['Mobile-Number']
    if args.get('Address-Line-1', None) is not None:
        address_line1 = args['Address-Line-1']
    if args.get('Address-Line-2', None) is not None:
        address_line2 = args['Address-Line-2']
    print("READ  EVERYTHING")
    print(email)
    count = 0
    for i in s:
        if i['EmailAddress'].find(email) != -1:
            contact_id = i['ContactID']
            print(contact_id)
            c = xero.contacts.get(contact_id)
            #print(c)
            if name != '':
                c[count]['Name'] = name
                print("NAME altered")
            if email != '':
                c[count]['EmailAddress'] = email
            if mobile != '':
                c[count]['Phones'][3]['PhoneNumber'] = mobile
            if address_line1 != '':
                c[count]['Addresses'][1]['AddressLine1'] = address_line1
            if address_line1 != '':
                c[count]['Addresses'][1]['AddressLine2'] = address_line2
            #Save updates
    xero.contacts.save(c)
    m = MessageClass()
    attachment = MessageAttachmentsClass()
    field = AttachmentFieldsClass()
    field.title = "Successfully updated the contact"
    attachment.attach_field(field)
    m.attach(attachment)
    return m
예제 #17
0
def search_contact(args, user_integration):
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    print("user integration-" + str(xcr.user_integration_id))
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }

    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    #print(new_credentials.state)
    s = xero.contacts.all()
    x = ''
    name = args['Name']
    print(name)
    for i in s:
        if i["FirstName"].find(name) != -1 or i['LastName'].find(
                name) != -1 or i['Name'].find(name) != -1:
            print(
                "CompanyName: " + i['Name'] + "\nFirst Name: " +
                i["FirstName"], " Last Name:",
                i['LastName'] + " \nEmail Address: " + i['EmailAddress'] +
                "  \nStreet Address: " + i['Addresses'][1]['AddressLine1'] +
                ", " + i['Addresses'][1]['AddressLine2'] + ", " +
                i['Addresses'][1]['AddressLine3'] + "\n," +
                i['Addresses'][1]['City'] + ", " +
                i['Addresses'][1]['Region'] + ", " +
                i['Addresses'][1]['Country'], i['Addresses'][1]['PostalCode'] +
                "\nPhone: " + i['Phones'][1]['PhoneCountryCode'],
                i['Phones'][1]['PhoneNumber'],
                i['Phones'][3]['PhoneCountryCode'],
                i['Phones'][3]['PhoneNumber'] + "\n" + "Contact ID: " +
                i['ContactID'] + "\n")
            x += "CompanyName: " + i['Name'] + "\nFirst Name: " + i[
                "FirstName"] + " Last Name:" + i[
                    'LastName'] + " \nEmail Address: " + i[
                        'EmailAddress'] + "  \nStreet Address: "
            x += i['Addresses'][1]['AddressLine1'] + ", " + i['Addresses'][1][
                'AddressLine2'] + ", "
            x += i['Addresses'][1]['AddressLine3'] + "\n," + i['Addresses'][1][
                'City'] + ", " + i['Addresses'][1]['Region'] + ", "
            x += "\nPhone No: " + i['Phones'][1]['PhoneCountryCode'] + " " + i[
                'Phones'][1]['PhoneNumber'] + " \n" + i['Phones'][3][
                    'PhoneCountryCode'] + " "
            x += i['Phones'][3]['PhoneNumber'] + "\n" + "Contact ID: " + i[
                'ContactID'] + "\n"
    if x == '':
        x = "Nothing Found matching your query"
    m = MessageClass()
    attachment = MessageAttachmentsClass()
    field = AttachmentFieldsClass()
    field.title = "The Contacts retrieved are:"
    field.value = x
    attachment.attach_field(field)
    m.attach(attachment)
    return m
예제 #18
0
    def list_users_today(self, args):
        #Check if 'sort' param is present, else assign default as 'asc'
        if 'sort' in args:
            if args['sort'] in ['asc', 'dsc']:
                order = args['sort']
            else:
                #If invalid, fallback to default value
                order = 'asc'
        else:
            #setting default order 'asc'
            order = 'asc'

        if 'subscription' in args:
            subscription = args['subscription']
        else:
            subscription = None

        #Instantiate a Message Object
        message = MessageClass()
        message.message_text = ""

        #Create list to store the results
        users_list = []

        d_24 = datetime.datetime.now() - datetime.timedelta(days=1)
        if subscription is None:
            users_today = SiteUsers.objects.filter(date_joined__gte=d_24)
        else:
            users_today = SiteUsers.objects.filter(date_joined__gte=d_24,
                                                   subscription=subscription)

        #Creating User attachments with information of users with a button to fetch user details using the "list_user_details" command
        for user in users_today:
            user_attachment = MessageAttachmentsClass()
            user_attachment.title = user.full_name

            #Showing user data in a "Field"
            date_field = AttachmentFieldsClass()
            date_field.title = "Date Joined"
            date_field.value = user.date_joined
            date_field.short = 1  #Utilize two columns
            user_attachment.attach_field(date_field)

            #Adding a button which calls the "list_user_details" command
            get_user_details_button = MessageButtonsClass()
            get_user_details_button.value = "1"  #Give some random value
            get_user_details_button.name = "1"  #Give some random value
            get_user_details_button.text = "Get user details"
            #Encoding command in button
            get_user_details_button.command = {
                "function_name": "list_user_details",
                "service_application": self.service_application,
                "data": {
                    "id": user.id
                }
            }
            user_attachment.attach_button(get_user_details_button)

            #Adding a button which provides with a dialog to change the subscription for the user using "change_user_subcription" function
            change_user_sub_button = MessageButtonsClass()
            change_user_sub_button.value = "1"  #Give some random value
            change_user_sub_button.name = "1"  #Give some random value
            change_user_sub_button.text = "Change subscription"
            #Encoding command in button
            change_user_sub_button.command = {
                "function_name": "change_user_subcription",
                "service_application": self.service_application,
                "data": {
                    "id": user.id
                },
                "inputs": ['subscription']
            }
            user_attachment.attach_button(change_user_sub_button)

            #Add attachment to message
            message.attach(user_attachment)

        #Adding users data to be used in workflows
        message.data = {"users": serializers.serialize("json", users_today)}
        return message.to_json()
예제 #19
0
    def search(self,args):
        print("In search")
        print(args)

        path = args['path']
        query = args['search']

        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        if path == '/':
            path = ""

        data = {"path": path,"query": query,"start": 0,"max_results": 100,"mode": "filename"}


        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/files/search', headers=headers, json=data)

        # Response check
        if r.status_code == requests.codes.ok:
            print("---------------")
            # Getting response in JSON
            r = r.content.decode("utf-8")
            response = json.loads(r)
            print(response)

            # Creating message using YA SDK
            message = MessageClass()

            if len(response['matches']) == 0:
                message.message_text = "No matches !\nPlease search again."
                return message.to_json()

            message.message_text = "Matches :"
            attachment = MessageAttachmentsClass()

            for i in range(0, len(response['matches'])):

                field1 = AttachmentFieldsClass()
                field1.title = "Path:"
                field1.value = response['matches'][i]['metadata']['path_display']
                attachment.attach_field(field1)

                field2 = AttachmentFieldsClass()
                field2.title = "Name :"
                field2.value = response['matches'][i]['metadata']['name']
                attachment.attach_field(field2)

                field3 = AttachmentFieldsClass()
                field3.title = "Type :"
                field3.value = response['matches'][i]['metadata']['.tag']
                attachment.attach_field(field3)

            message.attach(attachment)
            return message.to_json()
        else:
            print("Error")
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #20
0
    def get_message_byfolder(self, args):
        """This function returns the messages of a particular folder.
        The name of the folder is provided as input by the user.
        If the folder is Empty it returns 'Empty Folder' """
        print("In get_message_byfolder")
        folder_name = args["Folder-Name"]
        folder_name = folder_name.strip()
        folder_name = folder_name.replace(" ", "")
        get_foldermessages_url = graph_endpoint.format(
            '/me/mailfolders/{}/messages'.format(folder_name))

        query_parameters = {
            '$top': '10',
            '$select': 'receivedDateTime,subject,from',
            '$orderby': 'receivedDateTime DESC'
        }

        r = make_api_call('GET',
                          get_foldermessages_url,
                          self.access_token,
                          parameters=query_parameters)
        print(r.json())
        value = r.json()["value"]
        message = MessageClass()

        if len(value) == 0:
            message.message_text = "Empty Folder"
            return message.to_json()

        if r.status_code == requests.codes.ok:
            for i in range(0, len(value)):
                obj = value[i]

                id = obj["id"]
                bodyPreview = self.list_messages(args, id=id)

                attachment = MessageAttachmentsClass()
                attachment.title = "Subject"
                attachment.text = str(obj["subject"])

                field1 = AttachmentFieldsClass()
                field1.title = "Received Date Time"
                field1.value = str(obj["receivedDateTime"])
                attachment.attach_field(field1)

                if bodyPreview != None:
                    field2 = AttachmentFieldsClass()
                    field2.title = "Body Preview"
                    field2.value = str(bodyPreview)
                    attachment.attach_field(field2)

                from_obj = obj["from"]
                for j in range(0, len(from_obj)):
                    emailAddress = from_obj["emailAddress"]
                    field3 = AttachmentFieldsClass()
                    field3.title = "From"
                    field3.value = emailAddress["name"]
                    attachment.attach_field(field3)

                    field4 = AttachmentFieldsClass()
                    field4.title = "Email Id"
                    field4.value = emailAddress["address"]
                    attachment.attach_field(field4)

                message.attach(attachment)
                message.message_text = "messages are"
                print("returning mailfolder")
                if i == (len(value) - 1):
                    return message.to_json()
                else:
                    continue
        else:
            print(r.text)
            return "{0}: {1}".format(r.status_code, r.text)
예제 #21
0
    def create_folder(self, args):

        print("In create_folder")
        print(args)

        path = args['path']
        autorename = args['autorename']

        if autorename != 'true' and autorename != 'false':
            m = MessageClass()
            m.message_text = "Invalid value in autorename argument"
            return m.to_json()

        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        if autorename == 'true':
            autorename = True
        else:
            autorename = False

        data = {"path": path,"autorename": autorename}

        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/files/create_folder_v2', headers=headers, json=data)

        # Response check
        if r.status_code == requests.codes.ok:
            print("---------------")
            # Getting response in JSON
            r = r.content.decode("utf-8")
            response = json.loads(r)
            print(response)

            #Creating message using YA SDK
            message = MessageClass()
            attachment = MessageAttachmentsClass()

            attachment2 = MessageAttachmentsClass()
            message.message_text = "New folder successfully created"
            button = MessageButtonsClass()
            button.name = "1"
            button.value = "1"
            button.text = "Get folder details"
            button.command = {
                "service_application": str(self.user_integration.yellowant_integration_id),
                "function_name": 'get_all_folders',
                "data" :{"path": response['metadata']['path_display'],
               "recursive": True,
               "include_media_info": False,
               "include_deleted": False,
               "include_has_explicit_shared_members": False,
               "include_mounted_folders": True}
            }
            attachment2.attach_button(button)
            message.attach(attachment)
            message.attach(attachment2)
            return message.to_json()
        else:
            print("Error")
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #22
0
    def get_all_folders(self,args):

        print("In get_all_folders")

        # API call parameters for getting all customers
        path = args['path']

        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        if path == '/':
            path = ""

        data = {"path": path,
               "recursive": True,
               "include_media_info": False,
               "include_deleted": False,
               "include_has_explicit_shared_members": False,
               "include_mounted_folders": True}

        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/files/list_folder', headers=headers, json=data)

        # Error check
        if r.status_code == requests.codes.ok:

            # Getting response in JSON format
            response = r.content.decode("utf-8")
            response = json.loads(response)
            print(response)

            message = MessageClass()
            message.message_text = "List files and folders :"
            attachment = MessageAttachmentsClass()

            for i in range(0, len(response['entries'])):

                field1 = AttachmentFieldsClass()
                field1.title = "Name :"
                field1.value = response['entries'][i]['name']
                attachment.attach_field(field1)

                field2 = AttachmentFieldsClass()
                field2.title = "Type :"
                field2.value = response['entries'][i]['.tag']
                attachment.attach_field(field2)

            attachment2 = MessageAttachmentsClass()

            if response['has_more'] == True:
                button = MessageButtonsClass()
                button.name = "1"
                button.value = "1"
                button.text = "Get more files and folders"
                button.command = {
                    "service_application": str(self.user_integration.yellowant_integration_id),
                    "function_name": 'get_more_folders',
                    "data": {"cursor": response['cursor']}
                }
                attachment2.attach_button(button)
                message.attach(attachment)
                message.attach(attachment2)
                return message.to_json()

            message.attach(attachment)
            return message.to_json()
        else:
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #23
0
    def get_my_messages(self, args):
        """Returns the messages of the inbox folder"""
        print("In get_my_messages")
        get_messages_url = graph_endpoint.format(
            '/me/mailfolders/inbox/messages')

        # Use OData query parameters to control the results
        #  - Only first 10 results returned
        #  - Only return the ReceivedDateTime, Subject, and From fields
        #  - Sort the results by the ReceivedDateTime field in descending order
        query_parameters = {
            '$top': '10',
            '$select': 'receivedDateTime,subject,from',
            '$orderby': 'receivedDateTime DESC'
        }

        r = make_api_call('GET',
                          get_messages_url,
                          self.access_token,
                          parameters=query_parameters)
        if r.status_code == requests.codes.ok:

            r_json = r.json()
            obj1 = r_json["value"]
            print(r_json)
            message = MessageClass()
            for i in range(0, len(obj1)):
                obj = obj1[i]
                id = obj["id"]
                bodyPreview = self.list_messages(args, id=id)

                attachment = MessageAttachmentsClass()
                attachment.title = "Subject"
                attachment.text = str(obj["subject"])

                field1 = AttachmentFieldsClass()
                field1.title = "Received Date Time"
                field1.value = str(obj["receivedDateTime"])
                attachment.attach_field(field1)

                if bodyPreview != None:
                    field2 = AttachmentFieldsClass()
                    field2.title = "Body Preview"
                    field2.value = str(bodyPreview)
                    attachment.attach_field(field2)

                from_obj = obj["from"]
                for j in range(0, len(from_obj)):
                    emailAddress = from_obj["emailAddress"]
                    field3 = AttachmentFieldsClass()
                    field3.title = "From"
                    field3.value = emailAddress["name"]
                    attachment.attach_field(field3)

                    field4 = AttachmentFieldsClass()
                    field4.title = "Email Id"
                    field4.value = emailAddress["address"]
                    attachment.attach_field(field4)

                button1 = MessageButtonsClass()
                button1.text = "Forward"
                button1.value = "forward"
                button1.name = "forward"
                button1.command = {
                    "service_application":
                    self.user_integration.yellowant_integration_id,
                    "function_name": "forward_message",
                    "data": {
                        "Message-Id": str(obj["id"])
                    },
                    "inputs": ["toRecipients", "Message"]
                }

                attachment.attach_button(button1)

                button2 = MessageButtonsClass()
                button2.text = "Reply"
                button2.value = "Reply"
                button2.name = "Reply"
                button2.command = {
                    "service_application":
                    self.user_integration.yellowant_integration_id,
                    "function_name": "reply",
                    "data": {
                        "Message-Id": str(obj["id"])
                    },
                    "inputs": ["Message"]
                }

                attachment.attach_button(button2)

                message.attach(attachment)
            message.message_text = "Inbox messages are"

            return message.to_json()
        else:
            print(r.text)
            return "{0}: {1}".format(r.status_code, r.text)
예제 #24
0
def update_invoice(args, user_integration):
    #update by invoice number
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }
    new_credentials = PublicCredentials(**views.saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    s = xero.invoices.all()
    print(s)
    inv_number = 0
    amount_due = 0
    amount_paid = 0
    subtotal = 0
    total = 0
    print("Updating invoice...")

    if args.get("Invoice-Number", None) is not None:
        inv_number = args['Invoice-Number']
    if args.get("Amount-Due", None) is not None:
        amount_due = args['Amount-Due']
    if args.get("Amount-Paid", None) is not None:
        amount_paid = args['Amount-Paid']
    if args.get("SubTotal", None) is not None:
        subtotal = args['SubTotal']
    if args.get("Total", None) is not None:
        total = args['Total']
    flag = 0
    for i in s:
        if i['InvoiceNumber'] == inv_number:
            print("inside")
            flag = 1
            inv_id = i['InvoiceID']
            c = xero.invoices.get(inv_id)
            print("updating data...")
            #print(c)
            if amount_due != '':
                c[0]['AmountDue'] = amount_due
            if amount_paid != '':
                c[0]['AmountPaid'] = amount_paid
            if total != '':
                c[0]['Total'] = total
            print(c)

    m = MessageClass()
    attachment = MessageAttachmentsClass()
    field = AttachmentFieldsClass()
    if flag == 1:
        print("Updated successfully")
        xero.invoices.save(c)
        field.title = "Successfully updated the invoice"
    else:
        field.title = "Please Try again, Invalid Invoice Number"

    attachment.attach_field(field)
    m.attach(attachment)
    return m
예제 #25
0
def incident_triggered(request, webhook_id):
    """
        Webhook function to notify user about newly created incident
    """
    # Extracting necessary data
    data = request.body
    data_string = data.decode('utf-8')
    data_json = json.loads(data_string)

    name = data_json['display_name']
    entity_id = data_json['entity_id']
    incident_number = data_json['incident_number']
    # Fetching yellowant object
    yellow_obj = YellowUserToken.objects.get(webhook_id=webhook_id)
    access_token = yellow_obj.yellowant_token
    integration_id = yellow_obj.yellowant_integration_id
    service_application = str(integration_id)

    # Creating message object for webhook message
    webhook_message = MessageClass()
    webhook_message.message_text = "Incident Triggered\n The entity ID : " + str(entity_id)\
                                   + "\nThe Incident Number : " + str(incident_number) +\
                                   "\n Incident message : " + str(name)
    attachment = MessageAttachmentsClass()
    attachment.title = "Incident Operations"

    # button_get_incidents = MessageButtonsClass()
    # button_get_incidents.name = "1"
    # button_get_incidents.value = "1"
    # button_get_incidents.text = "Get all incidents"
    # button_get_incidents.command = {
    #     "service_application": service_application,
    #     "function_name": 'list_incidents',
    #     "data": {
    #         'data': "test",
    #     }
    # }
    #
    # attachment.attach_button(button_get_incidents)

    button_ack_incidents = MessageButtonsClass()
    button_ack_incidents.name = "2"
    button_ack_incidents.value = "2"
    button_ack_incidents.text = "Acknowledge the current incident"
    button_ack_incidents.command = {
        "service_application": service_application,
        "function_name": 'ack_incidents',
        "data": {
            "Incident-Numbers": incident_number,
        },
        "inputs": ["Acknowledgement-Message"]
    }

    attachment.attach_button(button_ack_incidents)

    webhook_message.attach(attachment)
    # print(integration_id)
    webhook_message.data = {
        "Display Name": name,
        "Entity ID": entity_id,
        "Incident Number": incident_number,
    }

    # Creating yellowant object
    yellowant_user_integration_object = YellowAnt(access_token=access_token)

    # Sending webhook message to user
    yellowant_user_integration_object.create_webhook_message(
        requester_application=integration_id,
        webhook_name="new_incident",
        **webhook_message.get_dict())

    return HttpResponse("OK", status=200)
예제 #26
0
    def share_folder(self, args):


        print("In share_folder")

        # Arguments from slack
        path = args["path"]
        member_policy = args['member_policy']
        shared_link_policy = args['shared_link_policy']

        if member_policy != 'anyone' and member_policy != "team":
            m = MessageClass()
            m.message_text = "Invalid value in member_policy argument"
            return m.to_json()

        if shared_link_policy != 'anyone' and shared_link_policy != "team":
            m = MessageClass()
            m.message_text = "Invalid value in shared_link_policy argument"
            return m.to_json()

        # API call parameters for getting all customer ids
        headers = {
            'Authorization': 'Bearer ' + self.dropbox_access_token,
            'Content-Type': 'application/json',
        }

        data = {"path": path,"acl_update_policy": "editors","force_async": False,"member_policy": member_policy ,"shared_link_policy": shared_link_policy}


        # Consuming the API
        r = requests.post('https://api.dropboxapi.com/2/sharing/share_folder', headers=headers, json=data)

        # Response check
        if r.status_code == requests.codes.ok:

            # Fetching response in JSON
            r = r.content.decode("utf-8")
            response = json.loads(r)
            print(response)

            # Creating a message object using YA SDK functions
            m = MessageClass()
            m.message_text = "Details for the shared folder : "
            attachment = MessageAttachmentsClass()

            field1 = AttachmentFieldsClass()
            field1.title = "Shared link : "
            field1.value = response['preview_url']
            attachment.attach_field(field1)

            field2 = AttachmentFieldsClass()
            field2.title = "Visibility :"
            field2.value = response['policy']['shared_link_policy']['.tag']
            attachment.attach_field(field2)

            field3 = AttachmentFieldsClass()
            field3.title = "Name :"
            field3.value = response['name']
            attachment.attach_field(field3)
            m.attach(attachment)
            return m.to_json()

        else:
            print("Error")
            m = MessageClass()
            print(r.content.decode("utf-8"))
            d = r.content.decode("utf-8")
            m.message_text = "{0}: {1}".format(r.status_code, r.text)
            return m.to_json()
예제 #27
0
def search_purchase_orders(
    args, user_integration
):  #search with purchasedate deliverydate or total cost or purchase order number or Company name
    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }

    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    string = args['Search-key']
    s = xero.purchaseorders.all()  #YYYYMMDD
    m = MessageClass()
    attachment = MessageAttachmentsClass()
    x = ''
    flag = 0
    for i in s:
        ddate = str(i['DeliveryDateString'])
        pdate = str(i['DateString'])
        if str(
                i['Total']
        ) == string != -1 or ddate == string or pdate == string or i[
                'PurchaseOrderNumber'].find(
                    string) != -1 or i['Contact']['Name'].find(string) != -1:
            flag = 1
            print("Purchase Order No.:", i['PurchaseOrderNumber'],
                  "Purchase Date: ", pdate, "Delivery Date: ", ddate,
                  "\nDelivery Address: ",
                  i['DeliveryAddress'] + " Telephone: ", i['Telephone'])
            print("Contact Name: ", i['Contact']['Name'], "Contact Address: ",
                  i['Contact']['Addresses'])
            print("Items: ", i['LineItems'][0]['Description'])
            print("Unit amount: ", i['LineItems'][0]['UnitAmount'],
                  "Quantity: ", i['LineItems'][0]['Quantity'],
                  "Discount Rate:", i['LineItems'][0]['DiscountRate'])
            print("Subtotal: ", i['SubTotal'], "Total:", i['Total'])
            x += "Purchase Order No.: " + str(
                i['PurchaseOrderNumber']
            ) + " Purchase Date: " + pdate + " Delivery Date: " + ddate + "\nDelivery Address: " + str(
                i['DeliveryAddress']) + " Telephone: " + str(i['Telephone'])
            x += " Contact Name: " + str(
                i['Contact']['Name']) + " Contact Address: " + str(
                    i['Contact']['Addresses'][1]["AddressLine1"])

            if str(i['Contact']['Addresses'][1]["AddressLine2"]) != '':
                x += str(i['Contact']['Addresses'][1]["AddressLine2"])
            if str(i['Contact']['Addresses'][1]["AddressLine3"]) != '':
                x += str(i['Contact']['Addresses'][1]["AddressLine3"])
            if str(i['Contact']['Addresses'][1]["AddressLine4"]) != '':
                x += str(i['Contact']['Addresses'][1]["AddressLine4"])
            x += "\nItems: " + str(i['LineItems'][0]['Description'])
            x += " Unit amount: " + str(
                i['LineItems'][0]['UnitAmount']) + " Quantity: " + str(
                    i['LineItems'][0]['Quantity']) + " Discount Rate: " + str(
                        i['LineItems'][0]['DiscountRate'])
            x += " Subtotal: " + str(i['SubTotal']) + "Total:" + str(
                i['Total'])
            field = AttachmentFieldsClass()
            field.title = "The purchase orders are:"
            field.value = x
            x = ''
            attachment.attach_field(field)
        if flag == 0:
            m.message_text = "Nothing found"
            return m
        m.attach(attachment)
        return m
예제 #28
0
def update_purchase_orders(
        args, user_integration):  #purchase order no used to update

    xcr = Xero_Credentials.objects.get(user_integration_id=user_integration.id)
    token = xcr.XERO_OAUTH_TOKEN
    secret = xcr.XERO_OAUTH_SECRET
    expire = xcr.XERO_EXPIRE
    auth = xcr.XERO_AUTH_EXPIRE
    fmt = '%Y%m%d%H%M%S%f'
    expire = datetime.datetime.strptime(expire, fmt)
    auth = datetime.datetime.strptime(auth, fmt)

    print("user integration-" + str(xcr.user_integration_id))
    print(expire)

    saved_state = {
        'consumer_key': 'BGJJ6JSSEAGIRWQ9SYKA1T3O7Y6IPF',
        'consumer_secret': '2JRHWN0QQ1K0AHVDZVUPKCVIQKUUNB',
        'callback_uri': 'http://127.0.0.1:8000/return/',
        'verified': True,
        'oauth_token': token,
        'oauth_token_secret': secret,
        'oauth_expires_at': expire,
        'oauth_authorization_expires_at': auth
    }
    new_credentials = PublicCredentials(**saved_state)
    print(new_credentials.state)
    xero = Xero(new_credentials)
    s = xero.purchaseorders.all()
    #print(s)
    p_no = 0
    p_no = args['PurchaseNumber']

    discount = 0
    tax_amt = 0
    quantity = 0
    if args.get("DiscountRate", None) is not None:
        discount = args['DiscountRate']
    if args.get("Quantity", None) is not None:
        quantity = args['Quantity']
    if args.get("Tax-Amount", None) is not None:
        tax_amt = args['Tax-Amount']
    flag = 0
    c = ''
    print("Updating purchase orders..." + str(p_no) + " " + str(discount))
    for i in s:
        if i['PurchaseOrderNumber'] == p_no:
            flag = 1
            po_id = i['PurchaseOrderID']
            #print(po_id)
            c = xero.purchaseorders.get(po_id)
            print(c)
            if discount != '':
                c[0]['DiscountRate'] = discount
            if quantity != '':
                c[0]['LineItems'][0]['Quantity'] = quantity
                print(c[0]['LineItems'][0]['Quantity'])
                line_total = float(c[0]['LineItems'][0]['LineAmount'])
                c[0]['LineItems'][0]['LineAmount'] = str(
                    float(quantity) *
                    float(c[0]['LineItems'][0]['UnitAmount'] *
                          (100 - c[0]['LineItems'][0]['DiscountRate']) / 100))
                c[0]['Total'] = str(
                    float(c[0]['Total']) - line_total +
                    float(c[0]['LineItems'][0]['LineAmount']))
                c[0]['SubTotal'] = c[0]['Total']

            if tax_amt != '':
                c[0]['TotalTax'] = tax_amt
                c[0]['Total'] = str(float(tax_amt) + float(c[0]['SubTotal']))
            #print(c)

    m = MessageClass()
    attachment = MessageAttachmentsClass()
    field = AttachmentFieldsClass()
    if flag == 1:
        print(c)
        field.title = 'Updated Purchase Order successfully'
        xero.purchaseorders.save(c)
    else:
        field.title = "Please try again, Invalid ID"
    attachment.attach_field(field)
    m.attach(attachment)
    return m
예제 #29
0
    def View_Survey_Details(self, args):
        # Gives the details of the survey(whichever the user chooses).
        print("In view_details")
        survey_id = args["SurveyId"]

        url = ("https://api.surveymonkey.com/v3/surveys/%s") % (survey_id)
        response = requests.get(url, headers=self.headers)
        response_json = response.json()
        print(response_json)
        title = response_json["title"]
        message = MessageClass()
        attachment = MessageAttachmentsClass()
        message.message_text = title

        field1 = AttachmentFieldsClass()
        field1.title = "Response Count"
        field1.value = response_json["response_count"]
        attachment.attach_field(field1)

        field2 = AttachmentFieldsClass()
        field2.title = "Date Created"
        field2.value = response_json["date_created"]
        attachment.attach_field(field2)

        field3 = AttachmentFieldsClass()
        field3.title = "Question Count"
        field3.value = response_json["question_count"]
        attachment.attach_field(field3)

        field4 = AttachmentFieldsClass()
        field4.title = "Category"
        field4.value = response_json["category"]
        attachment.attach_field(field4)

        field5 = AttachmentFieldsClass()
        field5.title = "Category"
        field5.value = response_json["category"]
        attachment.attach_field(field5)

        field7 = AttachmentFieldsClass()
        field7.title = "Ownership"
        field7.value = response_json["is_owner"]
        attachment.attach_field(field7)

        field8 = AttachmentFieldsClass()
        field8.title = "Date modified"
        field8.value = response_json["date_modified"]
        attachment.attach_field(field8)

        field6 = AttachmentFieldsClass()
        field6.title = "Survey Preview"
        field6.value = "<{}|Preview>".format(response_json["preview"])
        attachment.attach_field(field6)

        field9 = AttachmentFieldsClass()
        field9.title = "Analyze Survey"
        field9.value = "<{}|Analyze>".format(response_json["analyze_url"])
        attachment.attach_field(field9)

        field10 = AttachmentFieldsClass()
        field10.title = "Survey summary"
        field10.value = "<{}|Summary>".format(response_json["summary_url"])
        attachment.attach_field(field10)

        field11 = AttachmentFieldsClass()
        field11.title = "Edit survey"
        field11.value = "<{}|Edit>".format(response_json["edit_url"])
        attachment.attach_field(field11)

        field12 = AttachmentFieldsClass()
        field12.title = "View Response"
        field12.value = "<{}|Edit>".format(response_json["collect_url"])
        attachment.attach_field(field12)

        message.attach(attachment)

        # use inbuilt sdk method to_json to return message in a json format accepted by YA
        return message.to_json()