Пример #1
0
def update_status_current():
    message = request.json['message']
    rating = request.json['rating']
    session_id = request.json['session_id']
    if rating == 0 or rating == 1 or rating == 2 or rating == 3 or rating == 4 or rating == 5:
        rating = rating
    else:
        rating = 5
    if session_id != '':
        user_name = Users_v2.query.filter_by(id=session_id).first().username
        user_id = Users_v2.query.filter_by(id=session_id).first().id
        date_format = '%m-%d-%Y'
        date = datetime.datetime.now(tz=pytz.utc)
        date = date.astimezone(timezone('US/Pacific'))
        date_today = date.strftime(date_format)
        find_current_message = Messages.query.filter_by(
            pooper_name=user_name).order_by(
                Messages.id.desc()).limit(1).first().poop_message
        update_status_message = Messages.query.filter_by(
            poop_message=find_current_message).first().poop_message = message
        db.session.commit()
        update_status_rating = Messages.query.filter_by(
            poop_message=message).first().poop_rating = rating
        db.session.commit()
        # send_notifications(message,user_id) #no need to notify the people...thats a little aggressive
        return 'Success'
    return 'Falure'
Пример #2
0
def lambda_handler(event, context):
    
    # check admin status
    token = event['params']['header']['Authorization'][7:]
    url = "https://tqud77gtrh.execute-api.us-west-2.amazonaws.com/default/authorize/?token=" + token
    headers = {"Authorization":event['params']['header']['Authorization']}
    response = requests.get(url, headers=headers)
    json_data = json.loads(response.text)

    username = json_data.get('username')
    
    # set pacific time
    date_format='%m/%d/%Y %H:%M:%S %Z'
    date = datetime.now(tz=pytz.utc)
    date = date.astimezone(timezone('US/Pacific'))
    
    lastLogout = str(date.isoformat())
    response = table.scan()
    for i in response['Items']:
        if username == i['email']:
            i['lastLogout'] = lastLogout
            table.put_item(Item = i)
            return {"Status":"200"}

    raise Exception({
        "errorType" : "Exception",
        "httpStatus": 400
    })
    
Пример #3
0
def find_start_end_dates(dates):
    current_streak = 0
    date = datetime.datetime.today()
    date_pacific = date.astimezone(timezone('US/Pacific'))
    if str(date_pacific.strftime('%m-%d-%Y')) == str(dates[-1:][0]):
        start_date = dates[0]
        transpose_start_date = start_date.split('-')
        start_date = datetime.datetime(int(transpose_start_date[2]),
                                       int(transpose_start_date[0]),
                                       int(transpose_start_date[1]))
        next_day = ''
        for date in dates:
            transpose_date = date.split('-')
            date = datetime.datetime(int(transpose_date[2]),
                                     int(transpose_date[0]),
                                     int(transpose_date[1]))
            if next_day == '':
                next_day = date + datetime.timedelta(days=1)
            if date == next_day:
                next_date = date + datetime.timedelta(days=1)
                current_streak += 1
                next_day = next_date
            elif date != next_day:
                next_date = date + datetime.timedelta(days=1)
                current_streak = 0
                next_day = next_date
    return current_streak
Пример #4
0
def dateToDatetime(date):
    if date:
        date = date.split('/')
        date = datetime.datetime(int(date[2]), int(date[0]), int(date[1]))
        current_tz = timezone.get_current_timezone()
        date = date.astimezone(current_tz)
    return date
Пример #5
0
def isoformat(date):
    if date:
        if date.tzinfo:
            date = date.astimezone(datetime.timezone.utc)
            date = date.replace(tzinfo=None)
        date = date.replace(microsecond=0)
        return date.isoformat('T')
Пример #6
0
def get_events(day, service):
    
    date = datetime.datetime.combine(day, datetime.datetime.min.time())
    end_date = datetime.datetime.combine(day, datetime.datetime.max.time())
    utc = pytz.UTC
    date = date.astimezone(utc)
    end_date = end_date.astimezone(utc)

    events_result = service.events().list(calendarId='primary', timeMin=date.isoformat(), timeMax=end_date.isoformat(),
                                        singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        speak('Δεν έχεις τίποτα προγραμματισμένο')
    else:
        speak(f"Έχεις {len(events)} συμβάντα.") 
        
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            print(start, event['summary'])
            start_time = str(start.split("T")[1].split("+")[0])
            if int(start_time.split(":")[0]) < 12:
                start_time = start_time + "προ μεσημβρίαν"
            else:
                start_time = str(int(start_time.split(":")[0])-12)  +" "+ start_time.split(":")[1]
                start_time = start_time + "μετά μεσημβρίαν"

            speak(event["summary"] + " στις " + start_time)
Пример #7
0
    def __get_local_datetime(self, datetime_string):
        from_zone = tz.tzutc()
        to_zone = tz.tzlocal()

        date = dateutil.parser.parse(datetime_string)
        date.replace(tzinfo=from_zone)

        return date.astimezone(to_zone)
Пример #8
0
def isoformat(date):
    if date:
        if isinstance(date, datetime.date) and not isinstance(date, datetime.datetime):
            return date.isoformat()
        if date.tzinfo:
            date = date.astimezone(datetime.timezone.utc)
            date = date.replace(tzinfo=None)
        date = date.replace(microsecond=0)
        return date.isoformat("T")
Пример #9
0
def isoformat(date):
    if date:
        if (isinstance(date, datetime.date)
                and not isinstance(date, datetime.datetime)):
            return date.isoformat()
        if date.tzinfo:
            date = date.astimezone(datetime.timezone.utc)
            date = date.replace(tzinfo=None)
        date = date.replace(microsecond=0)
        return date.isoformat('T')
def datetime_to_iso_utc_string(date: datetime):
    '''
        Converts a date object into an 8601 string using UTC
    '''
    if date is None:
        return "None"

    try:
        return date.astimezone(pytz.UTC).isoformat()
    except Exception as e:
        raise ValidationError("Could not convert date to string", e)
 def _set_tz_awareness(self, date):
     if self.load_as_tz_aware:
         # If datetime is TZ naive, set UTC timezone
         if date.tzinfo is None or date.tzinfo.utcoffset(date) is None:
             date = date.replace(tzinfo=tzutc())
     else:
         # If datetime is TZ aware, convert it to UTC and remove TZ info
         if date.tzinfo is not None and date.tzinfo.utcoffset(
                 date) is not None:
             date = date.astimezone(tzutc())
         date = date.replace(tzinfo=None)
     return date
Пример #12
0
def add_year(date, posted=datetime.now()):
	if isinstance(posted, str):
		posted = dateutil.parser.parse(posted)
		posted = datetime(posted.year, posted.month, posted.day)
	#endif

	date = dateutil.parser.parse(date, tzinfos=tzinfos)
	if not date.tzinfo:
		date = date.astimezone(tz_pacific)

	if date < posted:
		return offset_year(date, 1)
	else:
		return date
Пример #13
0
    def persistSchedule(self, con, userId, date, sstart, send, isDayOfWeek=False, isDayOfMonth=False, isDayOfYear=False):
        uaware = date.astimezone(pytz.utc)

        # verifico que el start sea menor al end, sino supongo que el end es del dia siguiente
        if send < sstart:
            send += 24 * 60 * 60

        cur = con.cursor()
        cur.execute('set time zone %s', ('utc',))

        id = str(uuid.uuid4())
        req = (id, userId, uaware, sstart, send, isDayOfWeek, isDayOfMonth, isDayOfYear)
        cur.execute('insert into assistance.schedule (id,user_id,sdate,sstart,send,isDayOfWeek,isDayOfMonth,isDayOfYear) values (%s,%s,%s,%s,%s,%s,%s,%s)', req)
        return id
Пример #14
0
    def get_value_for_datastore(self, model_instance):
        '''Returns the value for writing to the datastore. If value is None,
        return None, else ensure date is converted to UTC. Note Google App
        Engine already does this. Called by datastore
        '''

        date = super(UtcDateTimeProperty,
                     self).get_value_for_datastore(model_instance)
        if date:
            if date.tzinfo:
                return date.astimezone(pytz.utc)
            else:
                return date.replace(tzinfo=pytz.utc)
        else:
            return None
Пример #15
0
def cadastro():

    if 'ContaInicial' in request.form and 'ContaFinal' in request.form and 'Valor' in request.form:
        date = datetime.now()
        fuso_horario = timezone('America/Sao_Paulo')
        data = date.astimezone(fuso_horario)
        mongo.db.users.insert({
            "ContaInicial": request.form.get('ContaInicial'),
            "ContaFinal": request.form.get('ContaFinal'),
            "Valor": request.form.get('Valor'),
            "date_ano": data.year,
            "date_mes": data.month,
            "date_dia": data.day,
            "date_hora": data.hour,
            "date_minuto": data.minute
        })
    return redirect(url_for('index'))
Пример #16
0
def update_status():
    message = request.json['message']
    rating = request.json['rating']
    session_id = request.json['session_id']
    if rating == 0 or rating == 1 or rating == 2 or rating == 3 or rating == 4 or rating == 5:
        rating = rating
    else:
        rating = 5
    if session_id != '':
        user_name = Users_v2.query.filter_by(id=session_id).first().username
        user_id = Users_v2.query.filter_by(id=session_id).first().id
        date_format = '%m-%d-%Y'
        date = datetime.datetime.now(tz=pytz.utc)
        date = date.astimezone(timezone('US/Pacific'))
        date_today = date.strftime(date_format)
        new_poop = Messages(pooper_name=user_name,
                            poop_date=date_today,
                            poop_message=message,
                            poop_rating=rating)
        db.session.add(new_poop)
        db.session.commit()
        send_notifications(message, user_id)
        return 'Success'
    return 'Falure'
Пример #17
0
 def localize_show_datetime(self, current_show):
     nextdate = current_show.get("RFC3339", "")
     process = True
     if len(nextdate) > 23:
         try:
             strdate, timezone = nextdate.rsplit("-", 1)
             offset = -1
         except:
             log("### error splitting next date (1)")
             process = False
         if process == False or len(timezone) < 3 or len(timezone) > 6:
             try:
                 strdate, timezone = nextdate.rsplit("+", 1)
                 offset = 1
             except:
                 log("### error splitting next date (2)")
                 process = False
     else:
         process = False
     if process == True:
         try:
             timezone = timezone.split(":")
         except:
             log("### error splitting next date (2)")
         timeoffset = timedelta(hours=offset * int(timezone[0]), minutes=offset * int(timezone[1]))
         date = datetime.fromtimestamp(mktime(strptime(strdate, "%Y-%m-%dT%H:%M:%S")))
         date = date.replace(
             tzinfo=tz.tzoffset(None, (offset * 3600 * int(timezone[0])) + (offset * 60 * int(timezone[1])))
         )
         log("### nextdate %s" % date.isoformat())
         datelocal = date.astimezone(tz.tzlocal())
         log("### nextdate with local time zone %s" % datelocal.isoformat())
         current_show["RFC3339"] = datelocal.isoformat()
         weekdaydiff = datelocal.weekday() - date.weekday()
         try:
             airday = current_show.get("Airtime").split(" at ")[0]
         except:
             airday = ""
             log("### error splitting airtime")
         if weekdaydiff != 0 and airday != "":
             try:
                 airdays = airday.split(" ,")
             except:
                 log("### error splitting airtime")
             for count, day in enumerate(airdays):
                 if day in self.days:
                     index = self.days.index(day)
                     airdays[count] = self.days[index + weekdaydiff]
             airday = ", ".join(airdays)
         if self.ampm:
             current_show["Airtime"] = airday + " at " + datelocal.strftime("%I:%M %p")
         else:
             current_show["Airtime"] = airday + " at " + datelocal.strftime("%H:%M")
         try:
             next = current_show.get("Next Episode").split("^")
             next.extend(["", ""])
         except:
             next = ["", "", ""]
         current_show["NextNumber"] = next[0]
         current_show["NextTitle"] = next[1]
         current_show["NextDate"] = datelocal.strftime(DATE_FORMAT)
     latest = current_show.get("Latest Episode", "").split("^")
     latest.extend(["", ""])
     if len(latest[2]) == 11:
         latesttime = strptime(latest[2], "%b/%d/%Y")
         date = datetime(latesttime[0], latesttime[1], latesttime[2])
         latest[2] = date.strftime(DATE_FORMAT)
     current_show["LatestNumber"] = latest[0]
     current_show["LatestTitle"] = latest[1]
     current_show["LatestDate"] = latest[2]
Пример #18
0
def lambda_handler(event, context):

    # check admin status
    token = event['params']['header']['Authorization'][7:]
    url = "https://tqud77gtrh.execute-api.us-west-2.amazonaws.com/default/authorize/?token=" + token
    headers = {"Authorization": event['params']['header']['Authorization']}
    response = requests.get(url, headers=headers)
    json_data = json.loads(response.text)

    # check not manager
    if 'Manager' in json_data['cognito:groups']:
        raise Exception({"errorType": "Exception", "httpStatus": 401})

    # if owner, check if have access to this issuer
    elif 'Owner' in json_data['cognito:groups']:
        response = tableUsers.scan()
        for i in response['Items']:
            json_str = json.dumps(i, cls=DecimalEncoder)
            resp_dict = json.loads(json_str)
            if resp_dict.get('email') == json_data['username']:
                if event['params']['path']['id'] not in resp_dict.get(
                        'ownedIssuers'):
                    raise Exception({
                        "errorType":
                        "Authorization",
                        "httpStatus":
                        401,
                        "message":
                        "Owner does not have access to this issuer"
                    })

    # Check if Issuer ID exists
    pID = event['params']['path']['id']
    tableBody = tableIssuers.query(KeyConditionExpression=Key('id').eq(pID))
    if tableBody['Count'] == 0:
        raise Exception({
            "errorType": "Exception",
            "httpStatus": 404,
            "message": "Issuer does not exist"
        })

    # if called by owner, cannot change owner
    if 'Owner' in json_data['cognito:groups']:
        event['body-json']['owner'] = tableBody['Items'][0]['owner']
    # check empty image
    if event['body-json']['image'] == None:
        event['body-json']['image'] = tableBody['Items'][0]['image']

    # check empty fields
    for i in event['body-json']:
        if i != 'owner':
            if len(event['body-json'][i]) == 0:
                raise Exception({
                    "errorType": "Empty",
                    "httpStatus": 400,
                    "message": "Empty Field"
                })

    response = tableIssuers.scan()
    # check existing name
    if event['body-json']['name'] != tableBody['Items'][0]['name']:
        for i in response['Items']:
            json_str = json.dumps(i, cls=DecimalEncoder)
            resp_dict = json.loads(json_str)
            if resp_dict.get('name') == event['body-json']['name']:
                raise Exception({
                    "errorType": "Conflict",
                    "httpStatus": 409,
                    "message": "Issuer name already exists"
                })

    # Revoke previous active key
    mList = []
    revocations = []
    for i in response['Items']:
        json_str = json.dumps(i, cls=DecimalEncoder)
        resp_dict = json.loads(json_str)
        if resp_dict.get('id') == pID:
            mList.append(resp_dict.get('key_info'))
            revocations = resp_dict.get('revocations')

    newPublicKey = True
    for i in mList[0]:
        if i['public_key'] == event['body-json']['publicKey']:
            newPublicKey = False
            break

    # set pacific time
    #date_format='%m/%d/%Y %H:%M:%S %Z'
    date = datetime.now(tz=pytz.utc)
    date = date.astimezone(timezone('US/Pacific'))

    if newPublicKey == True:

        # Revoke old key
        for i in mList[0]:
            if "revoked" not in i:
                i["revoked"] = str(date.isoformat())
                #i["revoked"] = str(datetime.now())

        # Set new active key
        mList[0].append({
            "public_key": event['body-json']['publicKey'],
            "private_key": event['body-json']['privateKey'],
            "created": str(date.isoformat())
        })

    # create data for blockcert.issuers
    data = {
        "id": pID,
        "name": event['body-json']['name'],
        "url": event['body-json']['url'],
        "email": event['body-json']['email'],
        "image": event['body-json']['image'],
        "key_info": mList[0],
        "revocations": revocations,
        "owner": event['body-json']['owner']
    }

    tableIssuers.put_item(Item=data)

    # update issuer profile in S3
    bucket = 'fs.blockcert.poc'
    key = 'issuers/' + str(pID) + '/profile'
    response = client.get_object(Bucket=bucket, Key=key)
    issuerProfile = json.loads(response['Body'].read().decode('utf-8'))

    issuerProfile['name'] = data['name']
    issuerProfile['url'] = data['url']
    issuerProfile['email'] = data['email']
    issuerProfile['image'] = data['image']
    issuerProfile['publicKey'] = [{
        "id": event['body-json']['publicKey'],
        "created": data['key_info'][-1]['created']
    }]

    fileobj = BytesIO(json.dumps(issuerProfile).encode())
    extraArgs = {'ACL': 'public-read', 'ContentType': 'application/json'}
    client.upload_fileobj(fileobj, bucket, key, ExtraArgs=extraArgs)

    # update blockcert.users
    ownedIssuers = []
    response = tableUsers.scan()
    userID = None
    for i in response['Items']:
        if i['email'] == event['body-json']['owner']:
            userID = i['id']
            ownedIssuers = i['ownedIssuers']
            if pID not in ownedIssuers:
                ownedIssuers.append(pID)
        # remove old owner
        if pID in i['ownedIssuers'] and i['id'] != userID:
            i['ownedIssuers'].remove(pID)
            response = tableUsers.update_item(
                Key={'id': i['id']},
                UpdateExpression="set ownedIssuers = :x",
                ExpressionAttributeValues={':x': i['ownedIssuers']},
                ReturnValues="UPDATED_NEW")
    # set new owner
    if userID != None:
        response = tableUsers.update_item(
            Key={'id': userID},
            UpdateExpression="set ownedIssuers = :x",
            ExpressionAttributeValues={':x': ownedIssuers},
            ReturnValues="UPDATED_NEW")

    return {"id": pID}
Пример #19
0
 def convert_date_to_local(self,date, tz):
     local = pytz.timezone(tz)
     date = date.replace(tzinfo=pytz.utc)
     date = date.astimezone(local)
     date.strftime('%Y-%m-%d: %H:%M:%S')
     return date.replace(tzinfo=None)
Пример #20
0
def timezoneAwareDate(date, tzinfo='Africa/Lagos'):
    try:
        realTzInfo = pytz.timezone(tzinfo)
        return date.astimezone(realTzInfo)
    except ValueError:
        return None
Пример #21
0
    def create_recurring_event(self, name, date_start, frequency, frequency_units, ends, **kwargs):
        from .models import RecurringEvent, RepeatInfo

        date = date_start
        max_duration = relativedelta(years=+1)
        date_max = date + max_duration

        rd_values = [
            relativedelta(days=+frequency),
            relativedelta(days=+(7 * frequency)),
            relativedelta(months=+frequency),
            relativedelta(years=+frequency),
        ]

        days_of_week = [
            'monday',
            'tuesday',
            'wednesday',
            'thursday',
            'friday',
            'saturday',
            'sunday',
        ]

        info = RepeatInfo.objects.create_repeat_info(frequency, frequency_units, ends, **kwargs)

        if ('weekday_list' in kwargs and kwargs['weekday_list']) or (frequency == 1 and frequency_units == 2):
            info.weekly = True
        else:
            info.weekly = False

        info.save()

        frequency_units -= 1

        if ends == 0: # ends after max. duration
            if 'date_end' in kwargs:
                date_end = kwargs['date_end']

                if 'weekday_list' in kwargs and kwargs['weekday_list']:
                    while date <= date_max:
                        if days_of_week[date.weekday()] in kwargs['weekday_list']:
                            event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                            event.date_end = date_end.astimezone(pytz.utc)

                            if 'location' in kwargs:
                                event.location = kwargs['location']

                            event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) + timedelta(days=1)
                        )
                        date_end = TZ.localize(
                            date_end.replace(tzinfo=None) + timedelta(days=1)
                        )
                else:
                    while date <= date_max:
                        event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                        event.date_end = date_end.astimezone(pytz.utc)

                        if 'location' in kwargs:
                            event.location = kwargs['location']

                        event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
                        date_end = TZ.localize(
                            date_end.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
            else:
                if 'weekday_list' in kwargs and kwargs['weekday_list']:
                    while date <= date_max:
                        if days_of_week[date.weekday()] in kwargs['weekday_list']:
                            event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                            if 'all_day' in kwargs:
                                event.all_day = kwargs['all_day']
                            else:
                                event.all_day = False

                            if 'location' in kwargs:
                                event.location = kwargs['location']

                            event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) + timedelta(days=1)
                        )
                else:
                    while date <= date_max:
                        event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                        if 'all_day' in kwargs:
                            event.all_day = kwargs['all_day']
                        else:
                            event.all_day = False

                        if 'location' in kwargs:
                            event.location = kwargs['location']
                        event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
        elif ends == 1: # ends on date
            if 'ends_on' not in kwargs:
                raise TypeError("create_recurring_event() missing 1 required keyword argument 'ends_on'")

            if 'date_end' in kwargs:
                date_end = kwargs['date_end']

                if 'weekday_list' in kwargs and kwargs['weekday_list']:
                    while date <= kwargs['ends_on'] and date <= date_max:
                        if days_of_week[date.weekday()] in kwargs['weekday_list']:
                            event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                            event.date_end = date_end.astimezone(pytz.utc)

                            if 'location' in kwargs:
                                event.location = kwargs['location']

                            event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) + timedelta(days=1)
                        )
                        date_end = TZ.localize(
                            date_end.replace(tzinfo=None) + timedelta(days=1)
                        )
                else:
                    while date <= kwargs['ends_on'] and date <= date_max:
                        event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                        event.date_end = date_end.astimezone(pytz.utc)

                        if 'location' in kwargs:
                            event.location = kwargs['location']

                        event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
                        date_end = TZ.localize(
                            date_end.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
            else:
                if 'weekday_list' in kwargs and kwargs['weekday_list']:
                    while date <= kwargs['ends_on'] and date <= date_max:
                        if days_of_week[date.weekday()] in kwargs['weekday_list']:
                            event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                            if 'all_day' in kwargs:
                                event.all_day = kwargs['all_day']
                            else:
                                event.all_day = False

                            if 'location' in kwargs:
                                event.location = kwargs['location']

                            event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) + timedelta(days=1)
                        )
                else:
                    while date <= kwargs['ends_on'] and date <= date_max:
                        event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                        if 'all_day' in kwargs:
                            event.all_day = kwargs['all_day']
                        else:
                            event.all_day = False

                        if 'location' in kwargs:
                            event.location = kwargs['location']

                        event.save()

                        date = TZ.localize(
                            date.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
        elif ends == 2: # ends after a number of occurrences
            if 'ends_after' not in kwargs:
                raise TypeError("create_recurring_event() missing 1 required keyword argument 'ends_after'")

            if 'date_end' in kwargs:
                date_end = kwargs['date_end']

                if 'weekday_list' in kwargs and kwargs['weekday_list']:
                    i = 0
                    while i < kwargs['ends_after'] and date <= date_max:
                        if days_of_week[date.weekday()] in kwargs['weekday_list']:
                            event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                            event.date_end = date_end.astimezone(pytz.utc)

                            if 'location' in kwargs:
                                event.location = kwargs['location']

                            event.save()

                            i += 1

                        date = TZ.localize(
                            date.replace(tzinfo=None) + timedelta(days=1)
                        )
                        date_end = TZ.localize(
                            date_end.replace(tzinfo=None) + timedelta(days=1)
                        )
                else:
                    i = 0
                    while i < kwargs['ends_after'] and date <= date_max:
                        event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                        event.date_end = date_end.astimezone(pytz.utc)

                        if 'location' in kwargs:
                            event.location = kwargs['location']

                        event.save()

                        i += 1
                        date = TZ.localize(
                            date.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
                        date_end = TZ.localize(
                            date_end.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )
            else:
                if 'weekday_list' in kwargs and kwargs['weekday_list']:
                    i = 0
                    while i < kwargs['ends_after'] and date <= date_max:
                        if days_of_week[date.weekday()] in kwargs['weekday_list']:
                            event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                            if 'all_day' in kwargs:
                                event.all_day = kwargs['all_day']
                            else:
                                event.all_day = False

                            if 'location' in kwargs:
                                event.location = kwargs['location']

                            event.save()

                            i += 1

                        date = TZ.localize(
                            date.replace(tzinfo=None) + timedelta(days=1)
                        )
                else:
                    i = 0
                    while i < kwargs['ends_after'] and date <= date_max:
                        event = self.create(name=name, date_start=date.astimezone(pytz.utc), info=info)

                        if 'all_day' in kwargs:
                            event.all_day = kwargs['all_day']
                        else:
                            event.all_day = False

                        if 'location' in kwargs:
                            event.location = kwargs['location']

                        event.save()

                        i += 1
                        date = TZ.localize(
                            date.replace(tzinfo=None) +
                            rd_values[frequency_units]
                        )

        return RecurringEvent.objects.filter(info=info)
Пример #22
0
def utcToLocalDatetime(date):
    if date:
        current_tz = timezone.get_current_timezone()
        date = date.astimezone(current_tz)
    return date
Пример #23
0
def utc_to_local(date):
    return date.astimezone(timezone.get_current_timezone())
Пример #24
0
def toISO(date: datetime, tz="Z"):
	return date.astimezone(dateutil.tz.UTC).isoformat().replace("+00:00", tz)
Пример #25
0
 def localize_show_datetime(self, current_show):
     nextdate = current_show.get("RFC3339", "")
     process = True
     if len(nextdate) > 23:
         try:
             strdate, timezone = nextdate.rsplit("-", 1)
             offset = -1
         except:
             log("### error splitting next date (1)")
             process = False
         if process == False or len(timezone) < 3 or len(timezone) > 6:
             try:
                 strdate, timezone = nextdate.rsplit("+", 1)
                 offset = 1
             except:
                 log("### error splitting next date (2)")
                 process = False
     else:
         process = False
     if process == True:
         try:
             timezone = timezone.split(":")
         except:
             log("### error splitting next date (2)")
         timeoffset = timedelta(hours=offset * int(timezone[0]),
                                minutes=offset * int(timezone[1]))
         date = datetime.fromtimestamp(
             mktime(strptime(strdate, '%Y-%m-%dT%H:%M:%S')))
         date = date.replace(
             tzinfo=tz.tzoffset(None, (offset * 3600 * int(timezone[0])) +
                                (offset * 60 * int(timezone[1]))))
         log('### nextdate %s' % date.isoformat())
         datelocal = date.astimezone(tz.tzlocal())
         log('### nextdate with local time zone %s' % datelocal.isoformat())
         current_show["RFC3339"] = datelocal.isoformat()
         weekdaydiff = datelocal.weekday() - date.weekday()
         try:
             airday = current_show.get("Airtime").split(" at ")[0]
         except:
             airday = ""
             log("### error splitting airtime")
         if weekdaydiff != 0 and airday != "":
             try:
                 airdays = airday.split(" ,")
             except:
                 log("### error splitting airtime")
             for count, day in enumerate(airdays):
                 if day in self.days:
                     index = self.days.index(day)
                     airdays[count] = self.days[index + weekdaydiff]
             airday = ', '.join(airdays)
         if self.ampm:
             current_show["Airtime"] = airday + " at " + datelocal.strftime(
                 '%I:%M %p')
         else:
             current_show["Airtime"] = airday + " at " + datelocal.strftime(
                 '%H:%M')
         try:
             next = current_show.get("Next Episode").split("^")
             next.extend(['', ''])
         except:
             next = ['', '', '']
         current_show["NextNumber"] = next[0]
         current_show["NextTitle"] = next[1]
         current_show["NextDate"] = datelocal.strftime(DATE_FORMAT)
     latest = current_show.get("Latest Episode", "").split("^")
     latest.extend(['', ''])
     if len(latest[2]) == 11:
         latesttime = strptime(latest[2], '%b/%d/%Y')
         date = datetime(latesttime[0], latesttime[1], latesttime[2])
         latest[2] = date.strftime(DATE_FORMAT)
     current_show["LatestNumber"] = latest[0]
     current_show["LatestTitle"] = latest[1]
     current_show["LatestDate"] = latest[2]
Пример #26
0
def change_utc_to_tz(date,timezone):
  from_zone = tz.gettz('UTC')
  to_zone = tz.gettz(timezone)

  date = date.replace(tzinfo=from_zone)
  return date.astimezone(to_zone)
Пример #27
0
    def update_from_google(self, cr, uid, event, single_event_dict, type, context):
        if context is None:
            context = []

        calendar_event = self.pool["calendar.event"]
        res_partner_obj = self.pool["res.partner"]
        calendar_attendee_obj = self.pool["calendar.attendee"]
        user_obj = self.pool.get("res.users")
        myPartnerID = user_obj.browse(cr, uid, uid, context).partner_id.id
        attendee_record = []
        partner_record = [(4, myPartnerID)]
        result = {}

        if single_event_dict.get("attendees", False):
            for google_attendee in single_event_dict["attendees"]:
                if type == "write":
                    for oe_attendee in event["attendee_ids"]:
                        if oe_attendee.email == google_attendee["email"]:
                            calendar_attendee_obj.write(
                                cr, uid, [oe_attendee.id], {"state": google_attendee["responseStatus"]}, context=context
                            )
                            google_attendee["found"] = True
                            continue

                if google_attendee.get("found", False):
                    continue
                attendee_id = res_partner_obj.search(
                    cr, uid, [("email", "=", google_attendee["email"])], context=context
                )
                if not attendee_id:
                    attendee_id = [
                        res_partner_obj.create(
                            cr,
                            uid,
                            {
                                "email": google_attendee["email"],
                                "Customer": False,
                                "name": google_attendee.get("displayName", False) or google_attendee["email"],
                            },
                            context=context,
                        )
                    ]
                attendee = res_partner_obj.read(cr, uid, attendee_id[0], ["email"], context=context)
                partner_record.append((4, attendee.get("id")))
                attendee["partner_id"] = attendee.pop("id")
                attendee["state"] = google_attendee["responseStatus"]
                attendee_record.append((0, 0, attendee))
        UTC = pytz.timezone("UTC")
        if single_event_dict.get("start") and single_event_dict.get("end"):  # If not cancelled
            if single_event_dict["start"].get("dateTime", False) and single_event_dict["end"].get("dateTime", False):
                date = parser.parse(single_event_dict["start"]["dateTime"])
                date_deadline = parser.parse(single_event_dict["end"]["dateTime"])
                delta = date_deadline.astimezone(UTC) - date.astimezone(UTC)
                date = str(date.astimezone(UTC))[:-6]
                date_deadline = str(date_deadline.astimezone(UTC))[:-6]
                allday = False
            else:
                date = single_event_dict["start"]["date"] + " 00:00:00"
                date_deadline = single_event_dict["end"]["date"] + " 00:00:00"
                d_start = datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
                d_end = datetime.strptime(date_deadline, "%Y-%m-%d %H:%M:%S")
                delta = d_end - d_start
                allday = True

            result["duration"] = (delta.seconds / 60) / 60.0 + delta.days * 24
            update_date = datetime.strptime(single_event_dict["updated"], "%Y-%m-%dT%H:%M:%S.%fz")
            result.update({"date": date, "date_deadline": date_deadline, "allday": allday})
        result.update(
            {
                "attendee_ids": attendee_record,
                "partner_ids": list(set(partner_record)),
                "name": single_event_dict.get("summary", "Event"),
                "description": single_event_dict.get("description", False),
                "location": single_event_dict.get("location", False),
                "class": single_event_dict.get("visibility", "public"),
                "oe_update_date": update_date,
                #            'google_internal_event_id': single_event_dict.get('id',False),
            }
        )

        if single_event_dict.get("recurrence", False):
            rrule = [rule for rule in single_event_dict["recurrence"] if rule.startswith("RRULE:")][0][6:]
            result["rrule"] = rrule

        if type == "write":
            res = calendar_event.write(cr, uid, event["id"], result, context=context)
        elif type == "copy":
            result["recurrence"] = True
            res = calendar_event.write(cr, uid, [event["id"]], result, context=context)

        elif type == "create":
            res = calendar_event.create(cr, uid, result, context=context)

        if context["curr_attendee"]:
            self.pool.get("calendar.attendee").write(
                cr,
                uid,
                [context["curr_attendee"]],
                {"oe_synchro_date": update_date, "google_internal_event_id": single_event_dict.get("id", False)},
                context,
            )
        return res
Пример #28
0
    def update_from_google(self, cr, uid, event, single_event_dict, type, context):
        if context is None:
            context= []

        calendar_event = self.pool['calendar.event']
        res_partner_obj = self.pool['res.partner']
        calendar_attendee_obj = self.pool['calendar.attendee']
        user_obj = self.pool.get('res.users')
        myPartnerID = user_obj.browse(cr,uid,uid,context).partner_id.id
        attendee_record = []
        partner_record = [(4,myPartnerID)]
        result = {}

        if single_event_dict.get('attendees',False):
            for google_attendee in single_event_dict['attendees']:
                if type == "write":
                    for oe_attendee in event['attendee_ids']:
                        if oe_attendee.email == google_attendee['email']:
                            calendar_attendee_obj.write(cr, uid,[oe_attendee.id] ,{'state' : google_attendee['responseStatus']},context=context)
                            google_attendee['found'] = True
                            continue

                if google_attendee.get('found',False):
                    continue
                attendee_id = res_partner_obj.search(cr, uid,[('email', '=', google_attendee['email'])], context=context)
                if not attendee_id:
                    attendee_id = [res_partner_obj.create(cr, uid,{'email': google_attendee['email'],'Customer': False, 'name': google_attendee.get("displayName",False) or google_attendee['email'] }, context=context)]
                attendee = res_partner_obj.read(cr, uid, attendee_id[0], ['email'], context=context)
                partner_record.append((4, attendee.get('id')))
                attendee['partner_id'] = attendee.pop('id')
                attendee['state'] = google_attendee['responseStatus']
                attendee_record.append((0, 0, attendee))
        UTC = pytz.timezone('UTC')
        if single_event_dict.get('start') and single_event_dict.get('end'): # If not cancelled   
            if single_event_dict['start'].get('dateTime',False) and single_event_dict['end'].get('dateTime',False):
                date = parser.parse(single_event_dict['start']['dateTime'])
                date_deadline = parser.parse(single_event_dict['end']['dateTime'])
                delta = date_deadline.astimezone(UTC) - date.astimezone(UTC)
                date = str(date.astimezone(UTC))[:-6]
                date_deadline = str(date_deadline.astimezone(UTC))[:-6]
                allday = False
            else:
                date = (single_event_dict['start']['date'] + ' 00:00:00')
                date_deadline = (single_event_dict['end']['date'] + ' 00:00:00')
                d_start = datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
                d_end = datetime.strptime(date_deadline, "%Y-%m-%d %H:%M:%S")
                delta = (d_end - d_start)
                allday = True

            result['duration'] = (delta.seconds / 60) / 60.0 + delta.days *24
            update_date = datetime.strptime(single_event_dict['updated'],"%Y-%m-%dT%H:%M:%S.%fz")
            result.update({
                'date': date,
                'date_deadline': date_deadline,
                'allday': allday
            })
        result.update({
            'attendee_ids': attendee_record,
            'partner_ids': list(set(partner_record)),

            'name': single_event_dict.get('summary','Event'),
            'description': single_event_dict.get('description',False),
            'location':single_event_dict.get('location',False),
            'class':single_event_dict.get('visibility','public'),
            'oe_update_date':update_date, 
#            'google_internal_event_id': single_event_dict.get('id',False),
        })

        if single_event_dict.get("recurrence",False):
            rrule = [rule for rule in single_event_dict["recurrence"] if rule.startswith("RRULE:")][0][6:]
            result['rrule']=rrule

        if type == "write":
            res = calendar_event.write(cr, uid, event['id'], result, context=context)
        elif type == "copy":
            result['recurrence'] = True
            res = calendar_event.write(cr, uid, [event['id']], result, context=context)

        elif type == "create":
            res = calendar_event.create(cr, uid, result, context=context)

        if context['curr_attendee']:
            self.pool.get('calendar.attendee').write(cr,uid,[context['curr_attendee']], {'oe_synchro_date':update_date,'google_internal_event_id': single_event_dict.get('id',False)},context)
        return res