Add helper function for timestamp

This commit is contained in:
JonnyWong16 2020-03-28 14:50:45 -07:00
parent c6cf293b12
commit f72d93216c
10 changed files with 37 additions and 29 deletions

View file

@ -112,7 +112,7 @@ class ActivityHandler(object):
ap.set_session_state(session_key=self.get_session_key(), ap.set_session_state(session_key=self.get_session_key(),
state=self.timeline['state'], state=self.timeline['state'],
view_offset=self.timeline['viewOffset'], view_offset=self.timeline['viewOffset'],
stopped=int(time.time())) stopped=helpers.timestamp())
def on_start(self): def on_start(self):
if self.is_valid_session(): if self.is_valid_session():
@ -188,7 +188,7 @@ class ActivityHandler(object):
# Set the session last_paused timestamp # Set the session last_paused timestamp
ap = activity_processor.ActivityProcessor() ap = activity_processor.ActivityProcessor()
ap.set_session_last_paused(session_key=self.get_session_key(), timestamp=int(time.time())) ap.set_session_last_paused(session_key=self.get_session_key(), timestamp=helpers.timestamp())
# Update the session state and viewOffset # Update the session state and viewOffset
self.update_db_session() self.update_db_session()
@ -252,7 +252,7 @@ class ActivityHandler(object):
if buffer_last_triggered: if buffer_last_triggered:
logger.debug("Tautulli ActivityHandler :: Session %s buffer last triggered at %s." % logger.debug("Tautulli ActivityHandler :: Session %s buffer last triggered at %s." %
(self.get_session_key(), buffer_last_triggered)) (self.get_session_key(), buffer_last_triggered))
time_since_last_trigger = int(time.time()) - int(buffer_last_triggered) time_since_last_trigger = helpers.timestamp() - int(buffer_last_triggered)
if current_buffer_count >= plexpy.CONFIG.BUFFER_THRESHOLD and time_since_last_trigger == 0 or \ if current_buffer_count >= plexpy.CONFIG.BUFFER_THRESHOLD and time_since_last_trigger == 0 or \
time_since_last_trigger >= plexpy.CONFIG.BUFFER_WAIT: time_since_last_trigger >= plexpy.CONFIG.BUFFER_WAIT:
@ -295,7 +295,7 @@ class ActivityHandler(object):
this_guid = last_guid this_guid = last_guid
# Check guid for live TV metadata every 60 seconds # Check guid for live TV metadata every 60 seconds
if db_session['live'] and int(time.time()) - db_session['stopped'] > 60: if db_session['live'] and helpers.timestamp() - db_session['stopped'] > 60:
metadata = self.get_metadata(skip_cache=True) metadata = self.get_metadata(skip_cache=True)
if metadata: if metadata:
this_guid = metadata['guid'] this_guid = metadata['guid']
@ -309,7 +309,7 @@ class ActivityHandler(object):
if this_state == 'playing': if this_state == 'playing':
# Update the session in our temp session table # Update the session in our temp session table
# if the last set temporary stopped time exceeds 60 seconds # if the last set temporary stopped time exceeds 60 seconds
if int(time.time()) - db_session['stopped'] > 60: if helpers.timestamp() - db_session['stopped'] > 60:
self.update_db_session() self.update_db_session()
# Start our state checks # Start our state checks
@ -598,7 +598,7 @@ def on_created(rating_key, **kwargs):
if metadata: if metadata:
notify = True notify = True
# now = int(time.time()) # now = helpers.timestamp()
# #
# if helpers.cast_to_int(metadata['added_at']) < now - 86400: # Updated more than 24 hours ago # if helpers.cast_to_int(metadata['added_at']) < now - 86400: # Updated more than 24 hours ago
# logger.debug("Tautulli TimelineHandler :: Library item %s added more than 24 hours ago. Not notifying." # logger.debug("Tautulli TimelineHandler :: Library item %s added more than 24 hours ago. Not notifying."

View file

@ -129,7 +129,7 @@ def check_active_sessions(ws_request=False):
else: else:
# Subsequent buffer notifications after wait time # Subsequent buffer notifications after wait time
if int(time.time()) > buffer_values[0]['buffer_last_triggered'] + \ if helpers.timestamp() > buffer_values[0]['buffer_last_triggered'] + \
plexpy.CONFIG.BUFFER_WAIT: plexpy.CONFIG.BUFFER_WAIT:
logger.info("Tautulli Monitor :: User '%s' has triggered multiple buffer warnings." logger.info("Tautulli Monitor :: User '%s' has triggered multiple buffer warnings."
% stream['user']) % stream['user'])
@ -165,7 +165,7 @@ def check_active_sessions(ws_request=False):
if not stream['stopped']: if not stream['stopped']:
# Set the stream stop time # Set the stream stop time
stream['stopped'] = int(time.time()) stream['stopped'] = helpers.timestamp()
monitor_db.action('UPDATE sessions SET stopped = ?, state = ? ' monitor_db.action('UPDATE sessions SET stopped = ?, state = ? '
'WHERE session_key = ? AND rating_key = ?', 'WHERE session_key = ? AND rating_key = ?',
[stream['stopped'], 'stopped', stream['session_key'], stream['rating_key']]) [stream['stopped'], 'stopped', stream['session_key'], stream['rating_key']])
@ -221,7 +221,7 @@ def check_recently_added():
with monitor_lock: with monitor_lock:
# add delay to allow for metadata processing # add delay to allow for metadata processing
delay = plexpy.CONFIG.NOTIFY_RECENTLY_ADDED_DELAY delay = plexpy.CONFIG.NOTIFY_RECENTLY_ADDED_DELAY
time_threshold = int(time.time()) - delay time_threshold = helpers.timestamp() - delay
time_interval = plexpy.CONFIG.MONITORING_INTERVAL time_interval = plexpy.CONFIG.MONITORING_INTERVAL
pms_connect = pmsconnect.PmsConnect() pms_connect = pmsconnect.PmsConnect()

View file

@ -143,7 +143,7 @@ class ActivityProcessor(object):
'channel_call_sign': session.get('channel_call_sign', ''), 'channel_call_sign': session.get('channel_call_sign', ''),
'channel_identifier': session.get('channel_identifier', ''), 'channel_identifier': session.get('channel_identifier', ''),
'channel_thumb': session.get('channel_thumb', ''), 'channel_thumb': session.get('channel_thumb', ''),
'stopped': int(time.time()) 'stopped': helpers.timestamp()
} }
keys = {'session_key': session.get('session_key', ''), keys = {'session_key': session.get('session_key', ''),
@ -157,7 +157,7 @@ class ActivityProcessor(object):
plexpy.NOTIFY_QUEUE.put({'stream_data': values.copy(), 'notify_action': 'on_play'}) plexpy.NOTIFY_QUEUE.put({'stream_data': values.copy(), 'notify_action': 'on_play'})
# If it's our first write then time stamp it. # If it's our first write then time stamp it.
started = int(time.time()) started = helpers.timestamp()
timestamp = {'started': started} timestamp = {'started': started}
self.db.upsert('sessions', timestamp, keys) self.db.upsert('sessions', timestamp, keys)
@ -200,11 +200,11 @@ class ActivityProcessor(object):
if str(session['stopped']).isdigit(): if str(session['stopped']).isdigit():
stopped = int(session['stopped']) stopped = int(session['stopped'])
else: else:
stopped = int(time.time()) stopped = helpers.timestamp()
elif session['stopped']: elif session['stopped']:
stopped = int(session['stopped']) stopped = int(session['stopped'])
else: else:
stopped = int(time.time()) stopped = helpers.timestamp()
self.set_session_state(session_key=session['session_key'], self.set_session_state(session_key=session['session_key'],
state='stopped', state='stopped',
stopped=stopped) stopped=stopped)
@ -575,7 +575,7 @@ class ActivityProcessor(object):
paused_counter = None paused_counter = None
for session in result: for session in result:
if session['last_paused']: if session['last_paused']:
paused_offset = int(time.time()) - int(session['last_paused']) paused_offset = helpers.timestamp() - int(session['last_paused'])
if session['paused_counter']: if session['paused_counter']:
paused_counter = int(session['paused_counter']) + int(paused_offset) paused_counter = int(session['paused_counter']) + int(paused_offset)
else: else:
@ -624,7 +624,7 @@ class ActivityProcessor(object):
return None return None
def set_temp_stopped(self): def set_temp_stopped(self):
stopped_time = int(time.time()) stopped_time = helpers.timestamp()
self.db.action('UPDATE sessions SET stopped = ?', [stopped_time]) self.db.action('UPDATE sessions SET stopped = ?', [stopped_time])
def increment_write_attempts(self, session_key=None): def increment_write_attempts(self, session_key=None):

View file

@ -223,6 +223,10 @@ def convert_seconds_to_minutes(s):
return 0 return 0
def timestamp():
return int(time.time())
def today(): def today():
today = datetime.date.today() today = datetime.date.today()
yyyymmdd = datetime.date.isoformat(today) yyyymmdd = datetime.date.isoformat(today)
@ -462,7 +466,7 @@ def create_https_certificates(ssl_cert, ssl_key):
from OpenSSL import crypto from OpenSSL import crypto
from certgen import createKeyPair, createSelfSignedCertificate, TYPE_RSA from certgen import createKeyPair, createSelfSignedCertificate, TYPE_RSA
serial = int(time.time()) serial = timestamp()
domains = ['DNS:' + d.strip() for d in plexpy.CONFIG.HTTPS_DOMAIN.split(',') if d] domains = ['DNS:' + d.strip() for d in plexpy.CONFIG.HTTPS_DOMAIN.split(',') if d]
ips = ['IP:' + d.strip() for d in plexpy.CONFIG.HTTPS_IP.split(',') if d] ips = ['IP:' + d.strip() for d in plexpy.CONFIG.HTTPS_IP.split(',') if d]
altNames = ','.join(domains + ips) altNames = ','.join(domains + ips)
@ -625,7 +629,7 @@ def is_valid_ip(address):
def update_geoip_db(): def update_geoip_db():
if plexpy.CONFIG.GEOIP_DB_INSTALLED: if plexpy.CONFIG.GEOIP_DB_INSTALLED:
logger.info(u"Tautulli Helpers :: Checking for GeoLite2 database updates.") logger.info(u"Tautulli Helpers :: Checking for GeoLite2 database updates.")
now = int(time.time()) now = timestamp()
if now - plexpy.CONFIG.GEOIP_DB_INSTALLED >= plexpy.CONFIG.GEOIP_DB_UPDATE_DAYS * 24 * 60 * 60: if now - plexpy.CONFIG.GEOIP_DB_INSTALLED >= plexpy.CONFIG.GEOIP_DB_UPDATE_DAYS * 24 * 60 * 60:
return install_geoip_db(update=True) return install_geoip_db(update=True)
logger.info(u"Tautulli Helpers :: GeoLite2 database already updated within the last %s days." logger.info(u"Tautulli Helpers :: GeoLite2 database already updated within the last %s days."
@ -712,7 +716,7 @@ def install_geoip_db(update=False):
logger.warn("Tautulli Helpers :: Failed to remove temporary GeoLite2 gzip file: %s" % e) logger.warn("Tautulli Helpers :: Failed to remove temporary GeoLite2 gzip file: %s" % e)
plexpy.CONFIG.__setattr__('GEOIP_DB', geolite2_db_path) plexpy.CONFIG.__setattr__('GEOIP_DB', geolite2_db_path)
plexpy.CONFIG.__setattr__('GEOIP_DB_INSTALLED', int(time.time())) plexpy.CONFIG.__setattr__('GEOIP_DB_INSTALLED', timestamp())
plexpy.CONFIG.write() plexpy.CONFIG.write()
logger.debug(u"Tautulli Helpers :: GeoLite2 database installed successfully.") logger.debug(u"Tautulli Helpers :: GeoLite2 database installed successfully.")
@ -960,7 +964,7 @@ def cloudinary_transform(rating_key=None, width=1000, height=1500, opacity=100,
img_options = {'format': img_format, img_options = {'format': img_format,
'fetch_format': 'auto', 'fetch_format': 'auto',
'quality': 'auto', 'quality': 'auto',
'version': int(time.time()), 'version': timestamp(),
'secure': True} 'secure': True}
if width != 1000: if width != 1000:

View file

@ -23,9 +23,11 @@ import time
import plexpy import plexpy
if plexpy.PYTHON_VERSION < 3: if plexpy.PYTHON_VERSION < 3:
import database import database
import helpers
import logger import logger
else: else:
from plexpy import database from plexpy import database
from plexpy import helpers
from plexpy import logger from plexpy import logger
@ -131,7 +133,7 @@ def delete_mobile_device(mobile_device_id=None):
def set_last_seen(device_token=None): def set_last_seen(device_token=None):
db = database.MonitorDatabase() db = database.MonitorDatabase()
last_seen = int(time.time()) last_seen = helpers.timestamp()
try: try:
result = db.action('UPDATE mobile_devices SET last_seen = ? WHERE device_token = ?', result = db.action('UPDATE mobile_devices SET last_seen = ? WHERE device_token = ?',

View file

@ -26,10 +26,12 @@ import email.utils
import plexpy import plexpy
if plexpy.PYTHON_VERSION < 3: if plexpy.PYTHON_VERSION < 3:
import database import database
import helpers
import logger import logger
import newsletters import newsletters
else: else:
from plexpy import database from plexpy import database
from plexpy import helpers
from plexpy import logger from plexpy import logger
from plexpy import newsletters from plexpy import newsletters
@ -144,7 +146,7 @@ def set_notify_state(newsletter, notify_action, subject, body, message, filename
if newsletter and notify_action: if newsletter and notify_action:
db = database.MonitorDatabase() db = database.MonitorDatabase()
keys = {'timestamp': int(time.time()), keys = {'timestamp': helpers.timestamp(),
'uuid': newsletter_uuid} 'uuid': newsletter_uuid}
values = {'newsletter_id': newsletter['id'], values = {'newsletter_id': newsletter['id'],

View file

@ -466,7 +466,7 @@ def set_notify_state(notifier, notify_action, subject='', body='', script_args='
script_args = json.dumps(script_args) if script_args else None script_args = json.dumps(script_args) if script_args else None
keys = {'timestamp': int(time.time()), keys = {'timestamp': helpers.timestamp(),
'session_key': session.get('session_key', None), 'session_key': session.get('session_key', None),
'rating_key': session.get('rating_key', None), 'rating_key': session.get('rating_key', None),
'user_id': session.get('user_id', None), 'user_id': session.get('user_id', None),
@ -826,7 +826,7 @@ def build_media_notify_params(notify_action=None, session=None, timeline=None, m
'week_number': now_iso[1], # Keep for backwards compatibility 'week_number': now_iso[1], # Keep for backwards compatibility
'datestamp': now.format(date_format), 'datestamp': now.format(date_format),
'timestamp': now.format(time_format), 'timestamp': now.format(time_format),
'unixtime': int(time.time()), 'unixtime': helpers.timestamp(),
'utctime': helpers.utc_now_iso(), 'utctime': helpers.utc_now_iso(),
# Stream parameters # Stream parameters
'streams': stream_count, 'streams': stream_count,
@ -1078,7 +1078,7 @@ def build_server_notify_params(notify_action=None, **kwargs):
'week_number': now_iso[1], # Keep for backwards compatibility 'week_number': now_iso[1], # Keep for backwards compatibility
'datestamp': now.format(date_format), 'datestamp': now.format(date_format),
'timestamp': now.format(time_format), 'timestamp': now.format(time_format),
'unixtime': int(time.time()), 'unixtime': helpers.timestamp(),
'utctime': helpers.utc_now_iso(), 'utctime': helpers.utc_now_iso(),
# Plex Media Server update parameters # Plex Media Server update parameters
'update_version': pms_download_info['version'], 'update_version': pms_download_info['version'],

View file

@ -2553,7 +2553,7 @@ class PUSHOVER(Notifier):
'sound': self.config['sound'], 'sound': self.config['sound'],
'html': self.config['html_support'], 'html': self.config['html_support'],
'priority': self.config['priority'], 'priority': self.config['priority'],
'timestamp': int(time.time())} 'timestamp': helpers.timestamp()}
if self.config['incl_subject']: if self.config['incl_subject']:
data['title'] = subject data['title'] = subject

View file

@ -615,7 +615,7 @@ class PmsConnect(object):
if metadata: if metadata:
_cache_time = metadata.pop('_cache_time', 0) _cache_time = metadata.pop('_cache_time', 0)
# Return cached metadata if less than cache_seconds ago # Return cached metadata if less than cache_seconds ago
if return_cache or int(time.time()) - _cache_time <= plexpy.CONFIG.METADATA_CACHE_SECONDS: if return_cache or helpers.timestamp() - _cache_time <= plexpy.CONFIG.METADATA_CACHE_SECONDS:
return metadata return metadata
if rating_key: if rating_key:
@ -1405,7 +1405,7 @@ class PmsConnect(object):
if metadata: if metadata:
if cache_key: if cache_key:
metadata['_cache_time'] = int(time.time()) metadata['_cache_time'] = helpers.timestamp()
out_file_folder = os.path.join(plexpy.CONFIG.CACHE_DIR, 'session_metadata') out_file_folder = os.path.join(plexpy.CONFIG.CACHE_DIR, 'session_metadata')
out_file_path = os.path.join(out_file_folder, 'metadata-sessionKey-%s.json' % cache_key) out_file_path = os.path.join(out_file_folder, 'metadata-sessionKey-%s.json' % cache_key)
@ -2749,7 +2749,7 @@ class PmsConnect(object):
web_img = img.startswith('http') web_img = img.startswith('http')
if refresh and not web_img: if refresh and not web_img:
img = '{}/{}'.format(img.rstrip('/'), int(time.time())) img = '{}/{}'.format(img.rstrip('/'), helpers.timestamp())
if web_img: if web_img:
params = {'url': '%s' % img} params = {'url': '%s' % img}

View file

@ -825,7 +825,7 @@ class Users(object):
if user_id is None or str(user_id).isdigit(): if user_id is None or str(user_id).isdigit():
monitor_db = database.MonitorDatabase() monitor_db = database.MonitorDatabase()
keys = {'timestamp': int(time.time()), keys = {'timestamp': helpers.timestamp(),
'user_id': user_id} 'user_id': user_id}
values = {'user': user, values = {'user': user,