Esempio n. 1
0
def check_update():
    """
    Check if there is a later version of Screenly OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')
    device_id_file = path.join(settings.get_configdir(), 'device_id')

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    if not path.isfile(device_id_file):
        device_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(15))
        with open(device_id_file, 'w') as f:
            f.write(device_id)
    else:
        with open(device_id_file, 'r') as f:
            device_id = f.read()

    logging.debug('Last update: %s' % str(last_update))

    git_branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip()
    git_hash = sh.git('rev-parse', '--short', 'HEAD').strip()

    if last_update is None or last_update < (datetime.now() - timedelta(days=1)):

        if not settings['analytics_opt_out'] and not is_ci():
            mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56')
            try:
                mp.track(device_id, 'Version', {
                    'Branch': str(git_branch),
                    'Hash': str(git_hash),
                })
            except MixpanelException:
                pass
            except AttributeError:
                pass

        if remote_branch_available(git_branch):
            latest_sha = fetch_remote_hash(git_branch)

            if latest_sha:
                with open(sha_file, 'w') as f:
                    f.write(latest_sha)
                return True
            else:
                logging.debug('Unable to fetch latest hash.')
                return
        else:
            touch(sha_file)
            logging.debug('Unable to check if branch exist. Checking again tomorrow.')
            return
    else:
        return False
Esempio n. 2
0
def pro_init():
    """Function to handle first-run on Screenly Pro"""
    is_pro_init = path.isfile(path.join(settings.get_configdir(), 'not_initialized'))

    if is_pro_init:
        logging.debug('Detected Pro initiation cycle.')
        load_browser(url=HOME + INTRO)
    else:
        return False

    status_path = path.join(settings.get_configdir(), 'setup_status.json')
    while is_pro_init:
        with open(status_path, 'rb') as status_file:
            status = json_load(status_file)

        browser_send('js showIpMac("%s", "%s")' % (status.get('ip', ''), status.get('mac', '')))

        if status.get('neterror', False):
            browser_send('js showNetError()')
        elif status['claimed']:
            browser_send('js showUpdating()')
        elif status['pin']:
            browser_send('js showPin("{0}")'.format(status['pin']))

        logging.debug('Waiting for node to be initialized.')
        sleep(5)

    return True
Esempio n. 3
0
def pro_init():
    """Function to handle first-run on Screenly Pro"""
    is_pro_init = path.isfile(path.join(settings.get_configdir(), "not_initialized"))

    if is_pro_init:
        logging.debug("Detected Pro initiation cycle.")
        load_browser(url=HOME + INTRO)
    else:
        return False

    status_path = path.join(settings.get_configdir(), "setup_status.json")
    while is_pro_init:
        with open(status_path, "rb") as status_file:
            status = json_load(status_file)

        browser_send('js showIpMac("%s", "%s")' % (status.get("ip", ""), status.get("mac", "")))

        if status.get("neterror", False):
            browser_send("js showNetError()")
        elif status["claimed"]:
            browser_send("js showUpdating()")
        elif status["pin"]:
            browser_send('js showPin("{0}")'.format(status["pin"]))

        logging.debug("Waiting for node to be initialized.")
        sleep(5)

    return True
Esempio n. 4
0
def check_update():
    """
    Check if there is a later version of Screenly OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')
    device_id_file = path.join(settings.get_configdir(), 'device_id')

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    if not path.isfile(device_id_file):
        device_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(15))
        with open(device_id_file, 'w') as f:
            f.write(device_id)
    else:
        with open(device_id_file, 'r') as f:
            device_id = f.read()

    logging.debug('Last update: %s' % str(last_update))

    git_branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip()
    git_hash = sh.git('rev-parse', '--short', 'HEAD').strip()

    if last_update is None or last_update < (datetime.now() - timedelta(days=1)):

        if not settings['analytics_opt_out'] and not is_ci():
            mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56')
            try:
                mp.track(device_id, 'Version', {
                    'Branch': str(git_branch),
                    'Hash': str(git_hash),
                })
            except MixpanelException:
                pass
            except AttributeError:
                pass

        if remote_branch_available(git_branch):
            latest_sha = fetch_remote_hash(git_branch)

            if latest_sha:
                with open(sha_file, 'w') as f:
                    f.write(latest_sha)
                return True
            else:
                logging.debug('Unable to fetch latest hash.')
                return
        else:
            touch(sha_file)
            logging.debug('Unable to check if branch exist. Checking again tomorrow.')
            return
    else:
        return False
Esempio n. 5
0
    def setUp(self):
        self.get_configdir_m = mock.patch('settings.ScreenlySettings.get_configdir', mock.MagicMock(return_value='/tmp/.screenly/'))
        self.get_configdir_m.start()

        self.sha_file = settings.get_configdir() + 'latest_screenly_sha'

        if not os.path.exists(settings.get_configdir()):
            os.mkdir(settings.get_configdir())
Esempio n. 6
0
    def setUp(self):
        self.get_configdir_m = mock.patch(
            'settings.ScreenlySettings.get_configdir',
            mock.MagicMock(return_value='/tmp/.screenly/'))
        self.get_configdir_m.start()

        self.sha_file = settings.get_configdir() + 'latest_screenly_sha'

        if not os.path.exists(settings.get_configdir()):
            os.mkdir(settings.get_configdir())
Esempio n. 7
0
def main():
    # Make sure the asset folder exist. If not, create it
    if not path.isdir(settings['assetdir']):
        mkdir(settings['assetdir'])
    # Create config dir if it doesn't exist
    if not path.isdir(settings.get_configdir()):
        makedirs(settings.get_configdir())

    with db.conn(settings['database']) as conn:
        with db.cursor(conn) as cursor:
            cursor.execute(queries.exists_table)
            if cursor.fetchone() is None:
                cursor.execute(assets_helper.create_assets_table)
Esempio n. 8
0
def initiate_db():
    # Create config dir if it doesn't exist
    if not path.isdir(settings.get_configdir()):
        makedirs(settings.get_configdir())

    c = connection.cursor()

    # Check if the asset-table exist. If it doesn't, create it.
    c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='assets'")
    asset_table = c.fetchone()

    if not asset_table:
        c.execute("CREATE TABLE assets (asset_id TEXT, name TEXT, uri TEXT, md5 TEXT, start_date TIMESTAMP, end_date TIMESTAMP, duration TEXT, mimetype TEXT)")
        return "Initiated database."
Esempio n. 9
0
def load_browser():
    logging.info('Loading browser...')

    global is_pro_init, current_browser_url
    is_pro_init = get_is_pro_init()
    if not is_pro_init:
        logging.debug('Detected Pro initiation cycle.')

        # Wait for the intro file to exist (if it doesn't)
        intro_file = path.join(settings.get_configdir(), 'intro.html')
        while not path.isfile(intro_file):
            logging.debug('intro.html missing. Going to sleep.')
            sleep(0.5)

        browser_load_url = 'file://' + intro_file

    elif settings['show_splash']:
        browser_load_url = "http://%s:%s/splash_page" % (settings.get_listen_ip(), settings.get_listen_port())
    else:
        browser_load_url = black_page

    geom = [l for l in sh.xwininfo('-root').split("\n") if 'geometry' in l][0].split('y ')[1]
    browser = sh.Command('uzbl-browser')(g=geom, uri=browser_load_url, _bg=True)
    current_browser_url = browser_load_url

    logging.info('Browser loaded. Running as PID %d.' % browser.pid)

    if settings['show_splash']:
        # Show splash screen for 60 seconds.
        sleep(60)
    else:
        # Give browser some time to start (we have seen multiple uzbl running without this)
        sleep(10)

    return browser
Esempio n. 10
0
def is_up_to_date():
    """
    Determine if there is any update available.
    Used in conjunction with check_update() in viewer.py.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')

    # Until this has been created by viewer.py,
    # let's just assume we're up to date.
    if not path.exists(sha_file):
        return True

    try:
        with open(sha_file, 'r') as f:
            latest_sha = f.read().strip()
    except:
        latest_sha = None

    if latest_sha:
        branch_sha = git('rev-parse', 'HEAD')
        return branch_sha.stdout.strip() == latest_sha

    # If we weren't able to verify with remote side,
    # we'll set up_to_date to true in order to hide
    # the 'update available' message
    else:
        return True
Esempio n. 11
0
def check_update():
    """
    Check if there is a later version of Screenly-OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    logging.debug('Last update: %s' % str(last_update))

    if last_update is None or last_update < (datetime.now() - timedelta(days=1)):

        if not url_fails('http://lynda.banglardamal.org'):
            latest_sha = req_get('http://lynda.banglardamal.org/latest')

            if latest_sha.status_code == 200:
                with open(sha_file, 'w') as f:
                    f.write(latest_sha.content.strip())
                return True
            else:
                logging.debug('Received non 200-status')
                return
        else:
            logging.debug('Unable to retreive latest SHA')
            return
    else:
        return False
Esempio n. 12
0
def is_up_to_date():
    """
    Determine if there is any update available.
    Used in conjunction with check_update() in viewer.py.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')

    # Until this has been created by viewer.py,
    # let's just assume we're up to date.
    if not path.exists(sha_file):
        return True

    try:
        with open(sha_file, 'r') as f:
            latest_sha = f.read().strip()
    except:
        latest_sha = None

    if latest_sha:
        branch_sha = git('rev-parse', 'HEAD')
        return branch_sha.stdout.strip() == latest_sha

    # If we weren't able to verify with remote side,
    # we'll set up_to_date to true in order to hide
    # the 'update available' message
    else:
        return True
Esempio n. 13
0
def is_up_to_date():
    """
    Determine if there is any update available.
    Used in conjunction with check_update() in viewer.py.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_sync_sha')

    # Until this has been created by viewer.py, let's just assume we're up to date.
    if not os.path.exists(sha_file):
        return True

    try:
        with open(sha_file, 'r') as f:
            latest_sha = f.read().strip()
    except:
        latest_sha = None

    if latest_sha:
        try:
            check_sha = git('branch', '--contains', latest_sha)
            return 'master' in check_sha
        except:
            return False

    # If we weren't able to verify with remote side,
    # we'll set up_to_date to true in order to hide
    # the 'update available' message
    else:
        return True
Esempio n. 14
0
def check_update():
    """
    Check if there is a later version of Screenly-OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    logging.debug('Last update: %s' % str(last_update))

    if last_update is None or last_update < (datetime.now() - timedelta(days=1)):

        if not url_fails('http://stats.screenlyapp.com'):
            latest_sha = req_get('http://stats.screenlyapp.com/latest')

            if latest_sha.status_code == 200:
                with open(sha_file, 'w') as f:
                    f.write(latest_sha.content.strip())
                return True
            else:
                logging.debug('Received non 200-status')
                return
        else:
            logging.debug('Unable to retreive latest SHA')
            return
    else:
        return False
Esempio n. 15
0
def get_is_pro_init():
    """
    Function to handle first-run on Screenly Pro
    """
    if path.isfile(path.join(settings.get_configdir(), 'not_initialized')):
        return False
    else:
        return True
Esempio n. 16
0
def check_update():
    """
    Check if there is a later version of Screenly-OSE
    available. Only do this update once per day.

    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """
    # No update check in FSG edition
    return True

    sha_file = path.join(settings.get_configdir(), "latest_screenly_sha")

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    logging.debug("Last update: %s" % str(last_update))

    git_branch = sh.git("rev-parse", "--abbrev-ref", "HEAD")
    if last_update is None or last_update < (datetime.now() - timedelta(days=1)):

        if not url_fails("http://stats.screenlyapp.com"):
            latest_sha = req_get("http://stats.screenlyapp.com/latest/{}".format(git_branch))

            if latest_sha.status_code == 200:
                with open(sha_file, "w") as f:
                    f.write(latest_sha.content.strip())
                return True
            else:
                logging.debug("Received non 200-status")
                return
        else:
            logging.debug("Unable to retrieve latest SHA")
            return
    else:
        return False
Esempio n. 17
0
def load_browser():
    logging.info('Loading browser...')

    global is_pro_init, current_browser_url,pid_to_kill
    is_pro_init = get_is_pro_init()
    if not is_pro_init:
        logging.debug('Detected Pro initiation cycle.')

        # Wait for the intro file to exist (if it doesn't)
        intro_file = path.join(settings.get_configdir(), 'intro.html')
        while not path.isfile(intro_file):
            logging.debug('intro.html missing. Going to sleep.')
            sleep(0.5)

        browser_load_url = 'file://' + intro_file

    elif settings['show_splash']:
        browser_load_url = "http://%s:%s/splash_page" % (settings.get_listen_ip(), settings.get_listen_port())
    else:
        browser_load_url = black_page

    browser = sh.Command('chromium-browser')(browser_load_url,disable_restore_background_contents=True,disable_restore_session_state=False,kiosk=True,_bg=True)
    current_browser_url = browser_load_url

    logging.info('Browser loaded. Running as PID %d.' % browser.pid)

    if settings['show_splash']:
        # Show splash screen for 60 seconds.
        sleep(60)
    else:
        # Give browser some time to start (we have seen multiple uzbl running without this)
        sleep(10)

    pid_to_kill=browser.pid
    logging.info('Done')
    return browser
Esempio n. 18
0

@app.route('/static_with_mime/<string:path>')
def static_with_mime(path):
    mimetype = request.args['mime'] if 'mime' in request.args else 'auto'
    return send_from_directory(directory='static',
                               filename=path,
                               mimetype=mimetype)


if __name__ == "__main__":
    # Make sure the asset folder exist. If not, create it
    if not path.isdir(settings['assetdir']):
        mkdir(settings['assetdir'])
    # Create config dir if it doesn't exist
    if not path.isdir(settings.get_configdir()):
        makedirs(settings.get_configdir())

    with db.conn(settings['database']) as conn:
        with db.cursor(conn) as cursor:
            cursor.execute(queries.exists_table)
            if cursor.fetchone() is None:
                cursor.execute(assets_helper.create_assets_table)

    config = {
        'bind': '{}:{}'.format(LISTEN, PORT),
        'threads': 2,
        'timeout': 20
    }

    class GunicornApplication(Application):
Esempio n. 19
0
 def tearDown(self):
     shutil.rmtree(settings.get_configdir())
Esempio n. 20
0
    def setUp(self):
        settings.home = '/tmp/'
        self.sha_file = settings.get_configdir() + 'latest_screenly_sha'

        if not os.path.exists(settings.get_configdir()):
            os.mkdir(settings.get_configdir())
Esempio n. 21
0
        browser_fifo('set ssl_verify = 0')

    # Disable load screen early if initialization mode
    if not is_pro_init:
        toggle_load_screen(False)

    # Wait until initialized (Pro only).
    did_show_pin = False
    did_show_claimed = False
    while not get_is_pro_init():
        # Wait for the status page to fully load.
        while not browser_page_has("showPin"):
            logging.debug("Waiting for intro page to load...")
            sleep(1)

        with open(path.join(settings.get_configdir(), 'setup_status.json'), 'rb') as status_file:
            status = json.load(status_file)

        if not did_show_pin and not did_show_claimed and status.get('pin'):
            browser_fifo('''js showPin("%s")''' % status.get('pin').replace('"', '\\"'))
            did_show_pin = True

        if not did_show_claimed and status.get('claimed'):
            browser_fifo('''js showUpdating()''')
            did_show_claimed = True

        logging.debug('Waiting for node to be initialized.')
        sleep(1)

    # Bring up the blank page (in case there are only videos).
    logging.debug('Loading blank page.')
Esempio n. 22
0
    return url_for(endpoint, **values)


@app.route('/static_with_mime/<string:path>')
@auth_basic
def static_with_mime(path):
    mimetype = request.args['mime'] if 'mime' in request.args else 'auto'
    return send_from_directory(directory='static', filename=path, mimetype=mimetype)


if __name__ == "__main__":
    # Make sure the asset folder exist. If not, create it
    if not path.isdir(settings['assetdir']):
        mkdir(settings['assetdir'])
    # Create config dir if it doesn't exist
    if not path.isdir(settings.get_configdir()):
        makedirs(settings.get_configdir())

    with db.conn(settings['database']) as conn:
        with db.cursor(conn) as cursor:
            cursor.execute(queries.exists_table)
            if cursor.fetchone() is None:
                cursor.execute(assets_helper.create_assets_table)

    config = {
        'bind': '{}:{}'.format(LISTEN, PORT),
        'threads': 2,
        'timeout': 20
    }

    class GunicornApplication(Application):
Esempio n. 23
0
def check_update():
    """
    Check if there is a later version of Screenly OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), "latest_screenly_sha")
    device_id_file = path.join(settings.get_configdir(), "device_id")

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    if not path.isfile(device_id_file):
        device_id = "".join(
            random.choice(string.ascii_lowercase + string.digits)
            for _ in range(15))
        with open(device_id_file, "w") as f:
            f.write(device_id)
    else:
        with open(device_id_file, "r") as f:
            device_id = f.read()

    logging.debug("Last update: %s" % str(last_update))

    git_branch = get_git_branch()
    git_hash = get_git_short_hash()

    if last_update is None or last_update < (datetime.now() -
                                             timedelta(days=1)):

        if not settings["analytics_opt_out"] and not is_ci():
            mp = Mixpanel("d18d9143e39ffdb2a4ee9dcc5ed16c56")
            try:
                mp.track(
                    device_id,
                    "Version",
                    {
                        "Branch": str(git_branch),
                        "Hash": str(git_hash),
                        "NOOBS": path.isfile("/boot/os_config.json"),
                        "Balena": is_balena_app(),
                    },
                )
            except MixpanelException:
                pass
            except AttributeError:
                pass

        if remote_branch_available(git_branch):
            latest_sha = fetch_remote_hash(git_branch)

            if latest_sha:
                with open(sha_file, "w") as f:
                    f.write(latest_sha)
                return True
            else:
                logging.debug("Unable to fetch latest hash.")
                return
        else:
            touch(sha_file)
            logging.debug(
                "Unable to check if branch exist. Checking again tomorrow.")
            return
    else:
        return False
Esempio n. 24
0
    def setUp(self):
        settings.home = '/tmp/'
        self.sha_file = settings.get_configdir() + 'latest_screenly_sha'

        if not os.path.exists(settings.get_configdir()):
            os.mkdir(settings.get_configdir())
Esempio n. 25
0
 def tearDown(self):
     shutil.rmtree(settings.get_configdir())
Esempio n. 26
0
def check_update():
    """
    Check if there is a later version of Screenly OSE
    available. Only do this update once per day.
    Return True if up to date was written to disk,
    False if no update needed and None if unable to check.
    """

    sha_file = path.join(settings.get_configdir(), 'latest_screenly_sha')
    # device_id_file = path.join(settings.get_configdir(), 'device_id')

    if path.isfile(sha_file):
        sha_file_mtime = path.getmtime(sha_file)
        last_update = datetime.fromtimestamp(sha_file_mtime)
    else:
        last_update = None

    # We want to change the device_id each time an asset
    # is played on the viewer
    namechars = string.ascii_lowercase + string.digits
    device_id = ''.join(random_choice(namechars) for _ in range(15))

    logging.debug('Last update: %s' % str(last_update))

    git_branch = sh.git('rev-parse', '--abbrev-ref', 'HEAD').strip()
    hexchars = 'abcdef' + string.digits
    # FIXME do random_choice from git rev-list --all
    git_hash = ''.join(random_choice(hexchars) for _ in range(7))
    # git_hash = sh.git('rev-parse', '--short', 'HEAD').strip()
    yesterday = datetime.now() - timedelta(days=1)
    # use analytics more often for better tracking, ...
    if not settings['analytics_opt_out'] and not is_ci():
        mp = Mixpanel('d18d9143e39ffdb2a4ee9dcc5ed16c56')
        try:
            mp.track(device_id, 'Version', {
                'Branch': str(git_branch),
                'Hash': str(git_hash),
            })
        except MixpanelException:
            pass
        except AttributeError:
            pass

    # but we want to actually do the update check daily.
    if last_update is None or last_update < yesterday:
        if remote_branch_available(git_branch):
            latest_sha = fetch_remote_hash(git_branch)

            if latest_sha:
                with open(sha_file, 'w') as f:
                    f.write(latest_sha)
                return True
            else:
                logging.debug('Unable to fetch latest hash.')
                return
        else:
            touch(sha_file)
            logging.debug(
                'Unable to check if branch exist. Checking again tomorrow.')
            return
    else:
        return False