Esempio n. 1
0
    def __init__(self, server_ip=None, username=None, db_name=None):
        if not (server_ip and username and db_name):
            config_file = utils.get_config_file()
            db_config = ConfigParser()
            db_config.read(config_file)

            db_config = db_config.__getitem__('database')

            server_ip = db_config.get('ip')
            username = db_config.get('username')
            db_name = db_config.get('db_name')

        connection = 'mysql+pymysql://' + username + '@' + server_ip + '/' + db_name
        LOG.debug('connection = %s', connection)
        engine = create_engine(connection, pool_recycle=3600)
        db_session = sessionmaker(bind=engine)
        self.session = db_session()
Esempio n. 2
0
    def __init__(self, local_dir, config_file):
        self.local_dir = local_dir
        LOG.debug('NFS runs in path: %s', self.local_dir)

        cfg = ConfigParser()
        cfg.read(config_file)

        nfs_config = cfg.__getitem__('nfs')

        self.nfs_ip = nfs_config.get('ip')
        self.nfs_dir = nfs_config.get('dir')
        self.ignore = nfs_config.get('ignore').replace(" ", "").split(',')

        table = PrettyTable()
        table.add_column('key', ['ip', 'dir', 'ignore'])
        table.add_column('value', [self.nfs_ip, self.nfs_dir, self.ignore])
        LOG.debug(table)
Esempio n. 3
0
def get_config(section):
    cfg = ConfigParser()
    cfg.read(CONFIG_FILE)
    return cfg.__getitem__(section)
Esempio n. 4
0
class SparrowServer(object):
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            print('Creating server object')
            cls._instance = super(SparrowServer, cls).__new__(cls)

        return cls._instance

    def __init__(self):
        # Read from config file
        self.cfg = ConfigParser()
        self.cfg.read(CONFIG_FILE)
        self.nfs_config = self.cfg.__getitem__('server')
        self.server_ip = self.nfs_config.get('ip')
        self.server_port = self.nfs_config.get('server_port')
        self.directory = self.nfs_config.get('directory')

        # Init flask and url mapping
        self.app = Flask(__name__,
                         template_folder='/opt/sparrow-player/templates',
                         static_folder='/opt/sparrow-player/static',
                         static_url_path='/static')

        self.app.add_url_rule('/', view_func=self.index, methods=['GET'])
        self.app.add_url_rule('/index.html',
                              view_func=self.index,
                              methods=['GET'])
        self.app.add_url_rule('/search',
                              view_func=self.search,
                              methods=['GET'])
        self.app.add_url_rule('/random_picks',
                              view_func=self.random_picks,
                              methods=['GET'])
        self.app.add_url_rule('/get_system_info',
                              view_func=self.get_system_info,
                              methods=['GET'])
        self.app.add_url_rule('/get_nfs_info',
                              view_func=self.get_nfs_info,
                              methods=['POST'])
        self.app.add_url_rule('/get_random_media',
                              view_func=self.get_random_media,
                              methods=['GET'])
        self.app.add_url_rule('/get_nodes_info',
                              view_func=self.get_nodes_info,
                              methods=['GET'])
        self.app.add_url_rule('/play/<target>/<int:media_id>',
                              view_func=self.play,
                              methods=['POST'])

        # Init medias
        self.medias = media_list.MediaList()
        # self.nodes = media_list.NodesTable()

    def random_picks(self):
        page = 1
        total_count = per_page = DISPLAY_PER_PAGE

        media_id_list = self.medias.get_random_slice(total_count)

        views_list = list()
        for media in media_id_list:
            a_view = dict()
            media_id = media.get('id')
            a_view['media_id'] = media_id

            if media.get('poster') is None:
                a_view['image'] = '/static/posters/Default.png'
            else:
                a_view['image'] = '/static/posters/' + str(media_id) + '.webp'

            a_view['time'] = '5:34'
            a_view['title'] = media.get('simple_name')
            views_list.append(a_view)

        pagination = Pagination(page=page,
                                total=total_count,
                                per_page=per_page)

        name_filter = 'Search...'

        return render_template('index.html',
                               views_list=views_list,
                               pagination=pagination,
                               name_filter=name_filter)

    def search(self):
        content = request.args.get('content')

        return self.index(name_filter=content)

    def index(self, name_filter=None):
        page = int(request.args.get('page', 1))
        per_page = DISPLAY_PER_PAGE
        total_count = self.medias.get_medias_count(name_filter=name_filter)

        # TODO: if page not exist, jump back to some error page
        start = (page - 1) * per_page
        end = page * per_page if total_count > page * per_page else total_count
        # id, simple_name, origin_name
        media_id_list = self.medias.get_slice(start,
                                              end,
                                              name_filter=name_filter)

        views_list = list()
        for media in media_id_list:
            a_view = dict()
            media_id = media.get('id')
            a_view['media_id'] = media_id

            if media.get('poster') is None:
                a_view['image'] = '/static/posters/Default.png'
            else:
                a_view['image'] = '/static/posters/' + str(media_id) + '.webp'

            a_view['time'] = '5:34'
            a_view['title'] = media.get('simple_name')
            views_list.append(a_view)

        pagination = Pagination(page=page,
                                total=total_count,
                                per_page=per_page)

        name_filter = name_filter if name_filter else 'Search...'

        return render_template('index.html',
                               views_list=views_list,
                               pagination=pagination,
                               name_filter=name_filter)

    def play(self, target, media_id):
        from sparrow_player.media_list import MediaList

        LOG.debug('*' * 100)
        LOG.debug(media_id)
        m = MediaList()
        if target == "main":
            server_ip = '192.168.0.66'
        else:
            server_ip = '192.168.0.88'

        server_port = '5001'
        media_path = m.get_media_path_by_id(media_id)
        media_title = m.get_media_title_by_path(media_path)

        play_info = {
            "media_path": media_path,
            "media_title": media_title,
        }

        LOG.debug(play_info)

        server_uri = server_ip + ':' + server_port
        url = 'http://' + server_uri + '/play_now'
        requests.put(url, data=json.dumps(play_info))

        return redirect(request.referrer)

    def get_nodes_info(self):
        nodes_info = list()
        all_nodes = self.medias.get_all_nodes()

        for node in all_nodes:
            node_info = {
                "node_ip": node['node_ip'],
                "node_name": node['node_name']
            }
            nodes_info.append(node_info)

        return jsonify(nodes_info)

    @staticmethod
    def get_system_info():
        system_info = {
            "system_name": str(os.popen('uname').read().split('\n')[0]),
            "startup_from": str(os.popen('uptime -s').read().split('\n')[0])
            # To add os start from
            # To add service start from
        }

        return jsonify(system_info)

    # Register node here
    def get_nfs_info(self):
        if not request.data:
            LOG.debug("no request data")

        info = request.data.decode('utf-8')
        info_json = json.loads(info)

        client_ip = info_json.get('client_ip')
        client_name = info_json.get('client_name')

        # Must validate ip information here.
        # self.nodes.update_node(client_ip, client_name)
        self.medias.update_node(client_ip, client_name)

        table = PrettyTable(['client ip', 'client host name'])
        table.add_row([client_ip, client_name])
        LOG.debug('\nNew connection established\n' '%s', table)

        mount_info = {"nfs_server": self.server_ip, "nfs_path": self.directory}
        return jsonify(mount_info)

    def get_random_media(self):
        media_path = self.medias.get_random_media_path()
        media_id = self.medias.get_id_by_path(media_path)
        media_title = self.medias.get_media_title_by_path(media_path)
        LOG.debug(
            'Random media generated, id=%(id)s, path=%(path)s, title=%(title)s',
            {
                'id': media_id,
                'path': media_path,
                'title': media_title
            })

        media_info = {"media_path": media_path, "media_title": media_title}
        self.medias.increase_played(media_id)

        return jsonify(media_info)

    def run(self):
        LOG.debug('Server start to listening on %(ip)s:%(port)s', {
            'ip': self.server_ip,
            'port': self.server_port
        })
        self.app.run(host=self.server_ip, port=int(self.server_port))