create_event.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

###########################
#######   LICENSE   #######
###########################

# Copyright (c) 2014-2016, Anodot Ltd. <info@anodot.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
#    following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
#    following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
#    products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import json
import logging
import argparse
import csv
import datetime
import time
from calendar import timegm
import requests
requests.packages.urllib3.disable_warnings()

#########################################################
# Function name: print_license                          #
# Params: None                                          #
# Returns: Anodot's license                             #
#########################################################
def print_license():
    text = '''
Copyright (c) 2014-2016, Anodot Ltd. <info@anodot.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
   following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
   following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
   products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    '''

    print(text)

#########################################################
# Function name: msg                                    #
# Params: None                                          #
# Returns: Returns the help message                     #
#########################################################
def msg(name=None):
    return '''create_event.py
         Create an event.

         - Print Anodot's license: python create_event.py --license
         - Create an event: python create_event.py --filename <The events CSV file> --token <the API's token> --timezone_shift <the timezone shift. Default is 0 (UTC). Value should be in seconds with the  +/- sign>
           Example: python create_event.py --filename myfile.csv --token 54673544263 --timezone_shift -5000
           Example: python create_event.py --filename myfile.csv --token 54673544263 --timezone_shift +3000
        '''


def main():
    logging.basicConfig(filename='create_event.log',level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
    logger = logging.getLogger(__name__)
    logger.info('Starting a run')

    parser = argparse.ArgumentParser(description='', usage=msg())
    parser.add_argument('--token', required=False, default=None, help="The Anodot's API token")
    parser.add_argument('--filename', required=False, default=None, help="The events CSV file")
    parser.add_argument('--timezone_shift', required=False, default="+0", help="Start time and end time timezone shift in seconds. Must be in the format +6000 or -6000. Default is UTC")
    parser.add_argument('--license', required=False, action='store_true', help="Print Anodot's license")

    args = parser.parse_args()

    if(args.license):
        logger.info('user asked to print the license')
        print_license()
        exit()

    if(args.token is None):
        logger.error('--token is mandatory when creating a new event')
        raise Exception ("--token is mandatory when creating a new event")
    elif(args.filename is None):
        logger.error('--filename is mandatory when creating a new event')
        raise Exception ("--filename is mandatory when creating a new event")
    elif(args.timezone_shift == "" or args.timezone_shift is None):
        logger.error('--timezone_shift is mandatory. timezone shift is in seconds. Must be in the format +6000 or -6000. Default is UTC')
        raise Exception ("--timezone_shift is mandatory. timezone shift is in seconds. Must be in the format +6000 or -6000. Default is UTC ")
    elif(str(args.timezone_shift)[0] != "+" and str(args.timezone_shift)[0] != "-"):
        logger.error('--timezone_shift is mandatory. timezone shift is in seconds. Must be in the format +6000 or -6000. Default is UTC')
        raise Exception ("--timezone_shift is mandatory. timezone shift is in seconds. Must be in the format +6000 or -6000. Default is UTC ")

    timezone_sign = str(args.timezone_shift)[0]
    timezone_shift = str(args.timezone_shift)[1:]
    row_counter = 0
    with open(args.filename, "rb") as source_file:
        reader = csv.reader(source_file, delimiter=",")
        reader.next()
        row_counter += 1
        for row in reader:
            title =  row[0]
            description = row[1]
            category =  row[2]
            source = row[3]
            start_time =  row[4]
            end_time = row[5]
            start_utc_time = None
            start_epoch_time = None
            end_utc_time = None
            end_epoch_time = None

            row_counter += 1
            if(title == "" or title is None):
                logger.error("Row " + str(row_counter) + ": title is missing")
                raise Exception ("Row " + str(row_counter) + ": title is missing")
            if(description == "" or title is None):
                description = "missing"
            if(category == "" or category is None):
                logger.error("Row " + str(row_counter) + ": category is missing")
                raise Exception ("Row " + str(row_counter) + ": category is missing")
            if(source == "" or source is None):
                logger.error("Row " + str(row_counter) + ": source is missing")
                raise Exception ("Row " + str(row_counter) + ": source is missing")
            if(start_time == "" or start_time is None):
                logger.error("Row " + str(row_counter) + ": start_time is missing")
                raise Exception ("Row " + str(row_counter) + ": start_time is missing")
            else:
                try:
                    start_utc_time = time.strptime(start_time, "%Y/%m/%d %H:%M")
                    start_epoch_time = timegm(start_utc_time)
                    if(timezone_sign == "+"):
                        start_epoch_time = int(start_epoch_time) + int(timezone_shift)
                    elif(timezone_sign == "-"):
                        start_epoch_time = int(start_epoch_time) - int(timezone_shift)
                except ValueError:
                    logger.error("Row " + str(row_counter) + ": start_time needs to be in the format: YYYY/MM/DD HH:MM")
                    raise Exception("Row " + str(row_counter) + ": start_time needs to be in the format: YYYY/MM/DD HH:MM")
            if(end_time != "" and end_time is not None):
                try:
                    end_utc_time = time.strptime(end_time, "%Y/%m/%d %H:%M")
                    end_epoch_time = timegm(end_utc_time)
                    if(timezone_sign == "+"):
                        end_epoch_time = end_epoch_time + int(timezone_shift)
                    elif(timezone_sign == "-"):
                        end_epoch_time = end_epoch_time - int(timezone_shift)

                except ValueError:
                    logger.error("Row " + str(row_counter) + ": end_time needs to be in the format: YYYY/MM/DD HH:MM")
                    raise Exception("Row " + str(row_counter) + ": end_time needs to be in the format: YYYY/MM/DD HH:MM")
            else:
                end_time = "missing"



            properties_arr = row[6:]
            properties = []
            for property in properties_arr:
                if (property is not None and property != ""):
                    if("=" in property):
                        tmp_property = property.split("=")
                        properties.append({"key": tmp_property[0], "value":tmp_property[1]})
                    else:
                        logger.error("Row " + str(row_counter) + ": property " + str(property) + " is not in the format of 'key=value'")
                        raise Exception("Row " + str(row_counter) + ": property " + str(property) + " is not in the format of 'key=value'")

            body = {"event": {"title": title, "category": category, "source": source, "startDate": str(start_epoch_time)}}
            if(description != "missing"):
                body["event"].update({"description": description})
            if(end_time != "missing"):
                body["event"].update({"endDate": end_epoch_time})
            if(properties != []):
                body["event"].update({"properties": properties})


            logger.info('Sending http request to create an event: ' +  json.dumps(body))
            response = requests.post('https://api.anodot.com/api/v1/user-events?token=' + args.token, headers={'Content-Type': 'application/json'}, data=json.dumps(body))
            if(response.status_code == 200):
                logger.info('Event was created: ' +  response.content)
                print "Event was created: " + response.content
            else:
                logger.error('Event creation failed: ' + 'status code: ' + str(response.status_code) + ' response body: ' + response.content)
                print 'Event creation failed: ' + 'status code: ' + str(response.status_code) + ' response body: ' + response.content

if __name__ == "__main__":
    main()
 

Was this article helpful?
0 out of 0 found this helpful