Sindbad~EG File Manager
# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT
from __future__ import absolute_import
from __future__ import division
import calendar
import datetime as datetimelib
from datetime import datetime, timedelta
import time
import re
from typing import Tuple
PARSE_PERIOD_PATTERN = re.compile(r'(\d+)(d|h|m|s)')
MAX_PERIOD_FOR_PARSING = 315360000 # 10 years
class _UTC(datetimelib.tzinfo):
"""UTC"""
def utcoffset(self, dt):
return datetimelib.timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return datetimelib.timedelta(0)
UTC = _UTC()
def gm_to_local(date_time):
"""
Converts date_time from UTC to local time
:param date_time:
:return:
"""
return datetime.fromtimestamp(calendar.timegm(date_time.timetuple()))
def local_to_gm(date_time):
"""
Converts date_time from local to UTC
:param date_time:
:return:
"""
return datetime.utcfromtimestamp(time.mktime(date_time.timetuple()))
def gm_datetime_to_unixtimestamp(dt=datetime.utcnow()):
"""
Converts utc datetime to timestamp
:param dt:
:return:
"""
return calendar.timegm(dt.timetuple())
def unixtimestamp_to_gm_datetime(ts):
"""
Converts timestamp to utc datetime
:param ts:
:return:
"""
return datetime.fromtimestamp(ts, tz=UTC)
def str_to_timedelta(period_str):
time_num = int(period_str[:-1])
time_type = period_str[-1]
if time_type == 'm':
return timedelta(minutes=time_num)
if time_type == 'h':
return timedelta(hours=time_num)
if time_type == 'd':
return timedelta(days=time_num)
raise ValueError(
'Error: period "{}" is incorrect. Please, specify '
'minutes with m, hours with h, days with d'.format(period_str))
def round_1m(dt):
return dt.replace(second=0, microsecond=0)
def parse_period(period_str, now=None):
"""
Parses string period (in local time),
example values such are 'today', 'yesterday', '5m', '4h', etc
:param period_str:str:
:param now:
:return:
"""
now = now or datetime.now()
val = period_str.lower()
if val == 'today':
return round_1m(now.replace(hour=0, minute=0)), now
elif val == 'yesterday':
today = round_1m(now.replace(hour=0, minute=0))
return today - timedelta(days=1), today
else:
return now - str_to_timedelta(period_str), now
def ts_to_iso(ts):
return gm_to_local(unixtimestamp_to_gm_datetime(ts)).isoformat()
def parse_date(date_str):
"""
Parses date time string specified into a naive date time object (timezone unaware),
that is expected to be in local time.
:param date_str:
:return:
"""
last_ex = []
for f in ('%Y-%m-%d', '%Y-%m-%d %H:%M', '%y-%m-%d %H:%M', '%y-%m-%d'):
try:
return datetime.strptime(date_str, f)
except ValueError as ex:
last_ex.append(ex)
raise ValueError("please use [YY]YY-MM-DD[ HH:MM] format", *last_ex)
def convert_to_seconds(td):
"""
Convert timedelta <type 'datetime.timedelta'> to seconds <type 'int'>
:param datetime.timedelta td: timedelta
:return int: seconds
"""
try:
return td.total_seconds()
except AttributeError: # no such method, fallback to old behavior, prior to python 2.7
# see https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) // 10**6
time_units = {
'd': 60 * 60 * 24,
'h': 60 * 60,
'm': 60,
's': 1,
}
units_of_time = {
'seconds': 's',
'minutes': 'm',
'hours': 'h',
'days': 'd',
}
def parse_period2(period):
"""
Return in seconds time period
support that format [D[D..]d][H[H..]h][M[M..]m][S[S..]][s] format; D[D..]d - D[D..] days, H[H..]h - H[H..] hours,
M[M..]m - M[M..] minutes, S[S..]s - S[S..] seconds
:param str period: period line
:return int: seconds
:raises: ValueError
"""
msg_ = '%s is incorrect; use today, yesterday or [D[D..]d][H[H..]h][M[M..]m][S[S..]][s] format; D[D..]d - D[D..] ' \
'days, H[H..]h - H[H..] hours, M[M..]m - M[M..] minutes, S[S..]s - S[S..] seconds' % (period,)
time_seconds = int(0)
length_of_matched_strings = 0
for dig, unit in PARSE_PERIOD_PATTERN.findall(period):
length_of_matched_strings += len(dig) + 1
time_seconds += int(dig) * time_units[unit]
if time_seconds > MAX_PERIOD_FOR_PARSING:
raise ValueError('%s is incorrect; period can not be more than 3600 days' % (period,))
if not time_seconds or length_of_matched_strings < len(period):
raise ValueError(msg_)
return time_seconds
def time_dict_to_seconds(time_dict):
"""
FIXME: we could avoid such extra conversions of units across various our
projects if we just use seconds everywhere and convert to other larger
units only before show them to end-user. Currently we parse/reconstruct
this ~3 times before we use in statsnotifier.py end-code.
:param time_dict: like {'period': 5, 'unitOfTime': 'seconds'}
:return: str '5s'
"""
return parse_period2('{}{}'.format(time_dict['period'],
units_of_time[time_dict['unitOfTime']]))
conversion_table = [
('days', 60 * 60 * 24),
('hours', 60 * 60),
('minutes', 60),
('seconds', 1),
]
def seconds_to_human_view(seconds) -> Tuple[int, str]:
"""
Convert provided second number to human view:
60 -> 1, 'minutes'
59 -> 59 , 'seconds'
3601 -> 1, 'hours'
:param seconds: Seconds number
:return: Tuple (number, english_name)
"""
for human_str, unit in conversion_table:
if seconds // unit > 0:
return seconds // unit, human_str
Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists