Exemple #1
0
    def getPlaylist(self):
        if is_android():
            return

        from Tribler.Main.vwxGUI import PLAYLIST_REQ_COLUMNS
        self._logger.debug("ChannelTorrent: fetching getPlaylistForTorrent from DB %s", self)

        playlist = self.channelcast_db.getPlaylistForTorrent(self.channeltorrent_id, PLAYLIST_REQ_COLUMNS)
        if playlist:
            return Playlist(*playlist + (self.channel,))
Exemple #2
0
    def __init__(self, sessconfig=None):
        """ Constructor.
        @param sessconfig Optional dictionary used internally
        to make this a copy constructor.
        """
        self._logger = logging.getLogger(self.__class__.__name__)

        self.selected_ports = {}
        self.sessconfig = sessconfig or CallbackConfigParser()

        # Poor man's versioning of SessionConfig, add missing default values.
        for section, sect_dict in sessdefaults.iteritems():
            if not self.sessconfig.has_section(section):
                self.sessconfig.add_section(section)
            for k, v in sect_dict.iteritems():
                if not self.sessconfig.has_option(section, k):
                    self.sessconfig.set(section, k, v)

        if not sessconfig:
            return

        # Set video_analyser_path
        if sys.platform == 'win32':
            ffmpegname = u"ffmpeg.exe"
        elif sys.platform == 'darwin':
            ffmpegname = u"ffmpeg"
        elif find_executable("avconv"):
            ffmpegname = u"avconv"
        else:
            ffmpegname = u"ffmpeg"

        ffmpegpath = find_executable(ffmpegname)
        if ffmpegpath is None:
            if sys.platform == 'darwin':
                self.sessconfig.set(u'general', u'videoanalyserpath', u"vlc/ffmpeg")
            elif is_android(strict=True):
                self.sessconfig.set(u'general', u'videoanalyserpath', os.path.join(
                    os.environ['ANDROID_PRIVATE'], 'ffmpeg'))
            else:
                self.sessconfig.set(u'general', u'videoanalyserpath', ffmpegname)
        else:
            self.sessconfig.set(u'general', u'videoanalyserpath', ffmpegpath)

        # Set videoplayer path
        if sys.platform == 'win32':
            videoplayerpath = os.path.expandvars('${PROGRAMFILES}') + '\\Windows Media Player\\wmplayer.exe'
        elif sys.platform == 'darwin':
            videoplayerpath = find_executable("vlc") or ("/Applications/VLC.app" if os.path.exists(
                "/Applications/VLC.app") else None) or "/Applications/QuickTime Player.app"
        else:
            videoplayerpath = find_executable("vlc") or "vlc"

        self.sessconfig.set(u'video', u'path', videoplayerpath)

        self.sessconfig.set(u'general', u'ipv6_binds_v4', autodetect_socket_style())
Exemple #3
0
    def getPlaylist(self):
        if is_android():
            return

        from Tribler.Main.vwxGUI import PLAYLIST_REQ_COLUMNS
        self._logger.debug(
            "ChannelTorrent: fetching getPlaylistForTorrent from DB %s", self)

        playlist = self.channelcast_db.getPlaylistForTorrent(
            self.channeltorrent_id, PLAYLIST_REQ_COLUMNS)
        if playlist:
            return Playlist(*playlist + (self.channel, ))
Exemple #4
0
    def subtitlefiles(self):
        if is_android():
            return []

        from Tribler.Main.vwxGUI import VLC_SUPPORTED_SUBTITLES
        subtitles = []
        for filename, length in self.files:
            prefix, ext = os.path.splitext(filename)
            if not ext.startswith('.'):
                ext = '.' + ext
            if ext in VLC_SUPPORTED_SUBTITLES:
                subtitles.append(filename)
        return subtitles
Exemple #5
0
    def subtitlefiles(self):
        if is_android():
            return []

        from Tribler.Main.vwxGUI import VLC_SUPPORTED_SUBTITLES
        subtitles = []
        for filename, length in self.files:
            prefix, ext = os.path.splitext(filename)
            if not ext.startswith('.'):
                ext = '.' + ext
            if ext in VLC_SUPPORTED_SUBTITLES:
                subtitles.append(filename)
        return subtitles
Exemple #6
0
    def avantar(self):
        if is_android():
            return None

        from Tribler.Main.vwxGUI.GuiImageManager import GuiImageManager, SMALL_ICON_MAX_DIM, data2wxBitmap
        gui_image_manager = GuiImageManager.getInstance()

        data = None
        if self.peer_id is None:
            mime, data = self.get_mugshot()
            if data:
                data = data2wxBitmap(mime, data, SMALL_ICON_MAX_DIM)

        if data is None:
            data = gui_image_manager.getImage(u"PEER_THUMB", SMALL_ICON_MAX_DIM)
        return data
Exemple #7
0
    def avantar(self):
        if is_android():
            return None

        from Tribler.Main.vwxGUI.GuiImageManager import GuiImageManager, SMALL_ICON_MAX_DIM, data2wxBitmap
        gui_image_manager = GuiImageManager.getInstance()

        data = None
        if self.peer_id is None:
            mime, data = self.get_mugshot()
            if data:
                data = data2wxBitmap(mime, data, SMALL_ICON_MAX_DIM)

        if data is None:
            data = gui_image_manager.getImage(u"PEER_THUMB",
                                              SMALL_ICON_MAX_DIM)
        return data
Exemple #8
0
def preferred_timecodes(videofile,
                        duration,
                        sample_res,
                        ffmpeg,
                        num_samples=20,
                        k=4):
    results = []
    dest_dir = tempfile.gettempdir()
    num_samples = min(num_samples, duration)

    for timecode in range(0, duration, duration / num_samples):
        outputfile = os.path.join(dest_dir, 'tn%d.jpg' % timecode)
        get_thumbnail(videofile, outputfile, sample_res, ffmpeg, timecode)
        if os.path.exists(outputfile):
            # Android doesn't have wx, use PIL instead
            if is_android():

                def get_image_data():
                    im = Image.open(outputfile)
                    return list(im.getdata())
            else:
                import wx
                from Tribler.Main.vwxGUI import forceAndReturnWxThread

                @forceAndReturnWxThread
                def get_image_data():
                    pxls = []
                    wxstr = wx.Bitmap(
                        outputfile,
                        wx.BITMAP_TYPE_ANY).ConvertToImage().GetData()
                    for index in range(0, len(wxstr), 3):
                        pxls.append(tuple(map(ord, wxstr[index:index + 3])))
                    return pxls

            this_colour = colourfulness(get_image_data())
            if this_colour is not None:
                results.append((this_colour, timecode))
                if os.path.exists(outputfile):
                    os.remove(outputfile)

    results.sort()
    results.reverse()
    topk = results[:k]
    return [item[1] for item in topk]
Exemple #9
0
def determine_install_dir():
    # Niels, 2011-03-03: Working dir sometimes set to a browsers working dir
    # only seen on windows

    # apply trick to obtain the executable location
    # see http://www.py2exe.org/index.cgi/WhereAmI
    # Niels, 2012-01-31: py2exe should only apply to windows

    # TODO(emilon): tribler_main.py is not frozen, so I think the special
    # treatment for windows could be removed (Needs to be tested)
    if sys.platform == 'win32':
        return get_base_path()
    elif sys.platform == 'darwin':
        return get_base_path()
    elif is_android():
        return os.path.abspath(os.path.join(unicode(os.environ['ANDROID_PRIVATE']), u'lib/python2.7/site-packages'))

    this_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
    return '/usr/share/tribler' if this_dir.startswith('/usr/lib') else this_dir
    def _connect(self):
        """
        Copies the libswift and ffmpeg binaries when on Android.
        :return:
        """

        if not self._connected:
            self._connected = True

            # Copy the swift and ffmpeg binaries
            if is_android(strict=True):
                binaries = ["swift", "ffmpeg"]

                for binary in binaries:
                    _logger.info("Setting up the %s binary.." % binary)

                    if not self._copy_binary(binary):
                        _logger.error("Unable to find or copy the %s binary!" % binary)
        else:
            raise RuntimeError("TriblerSession already connected")
    def _connect(self):
        """
        Copies the libswift and ffmpeg binaries when on Android.
        :return:
        """

        if not self._connected:
            self._connected = True

            # Copy the swift and ffmpeg binaries
            if is_android(strict=True):
                binaries = ['swift', 'ffmpeg']

                for binary in binaries:
                    _logger.info("Setting up the %s binary.." % binary)

                    if not self._copy_binary(binary):
                        _logger.error("Unable to find or copy the %s binary!" %
                                      binary)
        else:
            raise RuntimeError('TriblerSession already connected')
Exemple #12
0
    def _set_video_analyser_path(self):
        """
        Set the path of the video analyser.

        The path set depends on the current platform.
        :return:
        """
        if sys.platform == 'win32':
            # TODO: Remove this when migrating to Python 3
            #  This is to work around the case where windows has non-ASCII chars on %PATH% contents.
            from Tribler.Main.hacks import get_environment_variable
            path_env = get_environment_variable(u"PATH")
        elif is_android():
            path_env = unicode(os.environ["PYTHONPATH"])
        else:
            path_env = os.environ["PATH"]

        # Set video_analyser_path
        if sys.platform == 'win32':
            ffmpeg_name = u"ffmpeg.exe"
        elif sys.platform == 'darwin':
            ffmpeg_name = u"ffmpeg"
        elif find_executable("avconv", path_env):
            ffmpeg_name = u"avconv"
        else:
            ffmpeg_name = u"ffmpeg"

        ffmpeg_path = find_executable(ffmpeg_name, path_env)

        if ffmpeg_path is None:
            if sys.platform == 'darwin':
                self.config['general']['videoanalyserpath'] = "vlc/ffmpeg"
            else:
                self.config['general']['videoanalyserpath'] = os.path.abspath(
                    ffmpeg_name)
        else:
            self.config['general']['videoanalyserpath'] = os.path.abspath(
                ffmpeg_path)
Exemple #13
0
def preferred_timecodes(videofile, duration, sample_res, ffmpeg, num_samples=20, k=4):
    results = []
    dest_dir = tempfile.gettempdir()
    num_samples = min(num_samples, duration)

    for timecode in range(0, duration, duration / num_samples):
        outputfile = os.path.join(dest_dir, "tn%d.jpg" % timecode)
        get_thumbnail(videofile, outputfile, sample_res, ffmpeg, timecode)
        if os.path.exists(outputfile):
            # Android doesn't have wx, use PIL instead
            if is_android():

                def get_image_data():
                    im = Image.open(outputfile)
                    return list(im.getdata())

            else:
                import wx
                from Tribler.Main.vwxGUI import forceAndReturnWxThread

                @forceAndReturnWxThread
                def get_image_data():
                    pxls = []
                    wxstr = wx.Bitmap(outputfile, wx.BITMAP_TYPE_ANY).ConvertToImage().GetData()
                    for index in range(0, len(wxstr), 3):
                        pxls.append(tuple(map(ord, wxstr[index : index + 3])))
                    return pxls

            this_colour = colourfulness(get_image_data())
            if this_colour is not None:
                results.append((this_colour, timecode))
                if os.path.exists(outputfile):
                    os.remove(outputfile)

    results.sort()
    results.reverse()
    topk = results[:k]
    return [item[1] for item in topk]
Exemple #14
0
def determine_install_dir():
    # Niels, 2011-03-03: Working dir sometimes set to a browsers working dir
    # only seen on windows

    # apply trick to obtain the executable location
    # see http://www.py2exe.org/index.cgi/WhereAmI
    # Niels, 2012-01-31: py2exe should only apply to windows

    # TODO(emilon): tribler_main.py is not frozen, so I think the special
    # treatment for windows could be removed (Needs to be tested)
    if sys.platform == 'win32':
        return get_base_path()
    elif sys.platform == 'darwin':
        return get_base_path()
    elif is_android():
        return os.path.abspath(
            os.path.join(unicode(os.environ['ANDROID_PRIVATE']),
                         u'lib/python2.7/site-packages'))

    this_dir = os.path.abspath(
        os.path.join(os.path.dirname(__file__), '..', '..', '..'))
    return '/usr/share/tribler' if this_dir.startswith(
        '/usr/lib') else this_dir
Exemple #15
0
def return_feasible_playback_modes():
    l = []

    if sys.platform == 'darwin' or is_android():
        # TODO(paul): link or embed vlc in Android app
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
        return l

    try:
        # Make sure libvlc.dll will be found on windows
        if sys.platform.startswith('win'):
            env_entry = os.path.join(os.path.dirname(sys.argv[0]), "vlc")
            if not env_entry in os.environ['PATH']:
                os.environ['PATH'] += ";" + env_entry

            # Load libvlccore.dll manually so windows doesn't find a different one when loading libvlc.dll.
            import ctypes
            from ctypes import wintypes
            from contextlib import contextmanager

            def errcheck_dword(result, func, args):
                if result == 0:
                    last_error = ctypes.get_last_error()
                    if last_error != 0:
                        raise ctypes.WinError(last_error)
                return args

            def errcheck_bool(result, func, args):
                if not result:
                    last_error = ctypes.get_last_error()
                    if last_error != 0:
                        raise ctypes.WinError(last_error)
                    else:
                        raise OSError
                return args

            kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
            kernel32.GetDllDirectoryW.errcheck = errcheck_dword
            kernel32.GetDllDirectoryW.argtypes = (
                wintypes.DWORD,  # _In_  nBufferLength
                wintypes.LPWSTR)  # _Out_ lpBuffer

            kernel32.SetDllDirectoryW.errcheck = errcheck_bool
            kernel32.SetDllDirectoryW.argtypes = (wintypes.LPCWSTR,
                                                  )  # _In_opt_ lpPathName

            @contextmanager
            def use_dll_dir(dll_dir):
                size = newsize = 0
                while newsize >= size:
                    size = newsize
                    prev = (ctypes.c_wchar * size)()
                    newsize = kernel32.GetDllDirectoryW(size, prev)
                    kernel32.SetDllDirectoryW(os.path.abspath(dll_dir))
                try:
                    yield
                finally:
                    kernel32.SetDllDirectoryW(prev)

            with use_dll_dir(env_entry):
                import Tribler.vlc as vlc
        else:
            import Tribler.vlc as vlc

        # Niels: check version of vlc
        version = vlc.libvlc_get_version()
        subversions = version.split(".")
        if len(subversions) > 2:
            version = subversions[0] + "." + subversions[1]
        version = float(version)
        if version < 0.9:
            raise Exception(
                "Incorrect vlc version. We require at least version 0.9, this is %s"
                % version)

        l.append(PLAYBACKMODE_INTERNAL)
    except NameError:
        logger.error(
            "libvlc_get_version couldn't be called, no playback possible")
    except Exception:
        print_exc()

    if sys.platform == 'win32':
        l.append(PLAYBACKMODE_EXTERNAL_MIME)
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
    else:
        l.append(PLAYBACKMODE_EXTERNAL_DEFAULT)
    return l
Exemple #16
0
    def __init__(self, sessconfig=None):
        """ Constructor.
        @param sessconfig Optional dictionary used internally
        to make this a copy constructor.
        """
        self._logger = logging.getLogger(self.__class__.__name__)

        self.selected_ports = {}
        self.sessconfig = sessconfig or CallbackConfigParser()

        # Poor man's versioning of SessionConfig, add missing default values.
        for section, sect_dict in sessdefaults.iteritems():
            if not self.sessconfig.has_section(section):
                self.sessconfig.add_section(section)
            for k, v in sect_dict.iteritems():
                if not self.sessconfig.has_option(section, k):
                    self.sessconfig.set(section, k, v)

        if not sessconfig:
            return

        if sys.platform == 'win32':
            # TODO(emilon): This is to work around the case where windows has
            # non-ASCI chars on %PATH% contents. Should be removed if we migrate to
            # python 3.
            from Tribler.Main.hacks import get_environment_variable
            path_env = get_environment_variable(u"PATH")
        elif is_android():
            path_env = unicode(os.environ["PYTHONPATH"])
        else:
            path_env = os.environ["PATH"]

        # Set video_analyser_path
        if sys.platform == 'win32':
            ffmpegname = u"ffmpeg.exe"
        elif sys.platform == 'darwin':
            ffmpegname = u"ffmpeg"
        elif find_executable("avconv", path_env):
            ffmpegname = u"avconv"
        else:
            ffmpegname = u"ffmpeg"

        ffmpegpath = find_executable(ffmpegname, path_env)

        if ffmpegpath is None:
            if sys.platform == 'darwin':
                self.sessconfig.set(u'general', u'videoanalyserpath',
                                    u"vlc/ffmpeg")
            else:
                self.sessconfig.set(u'general', u'videoanalyserpath',
                                    os.path.abspath(ffmpegname))
        else:
            self.sessconfig.set(u'general', u'videoanalyserpath',
                                os.path.abspath(ffmpegpath))

        # Set videoplayer path
        if sys.platform == 'win32':
            videoplayerpath = os.path.expandvars(
                '${PROGRAMFILES}') + '\\Windows Media Player\\wmplayer.exe'
        elif sys.platform == 'darwin':
            videoplayerpath = find_executable("vlc") or (
                "/Applications/VLC.app"
                if os.path.exists("/Applications/VLC.app") else
                None) or "/Applications/QuickTime Player.app"
        else:
            videoplayerpath = find_executable("vlc") or "vlc"

        self.sessconfig.set(u'video', u'path', videoplayerpath)

        self.sessconfig.set(u'general', u'ipv6_binds_v4',
                            autodetect_socket_style())
Exemple #17
0
 def test_is_android(self):
     if sys.platform.startswith('linux') and 'ANDROID_PRIVATE' in os.environ:
         self.assertTrue(is_android())
     else:
         self.assertFalse(is_android())
Exemple #18
0
    def __init__(self, sessconfig=None):
        """ Constructor.
        @param sessconfig Optional dictionary used internally
        to make this a copy constructor.
        """
        self._logger = logging.getLogger(self.__class__.__name__)

        self.selected_ports = {}
        self.sessconfig = sessconfig or CallbackConfigParser()

        # Poor man's versioning of SessionConfig, add missing default values.
        for section, sect_dict in sessdefaults.iteritems():
            if not self.sessconfig.has_section(section):
                self.sessconfig.add_section(section)
            for k, v in sect_dict.iteritems():
                if not self.sessconfig.has_option(section, k):
                    self.sessconfig.set(section, k, v)

        if not sessconfig:
            return

        # Set video_analyser_path
        if sys.platform == 'win32':
            ffmpegname = u"ffmpeg.exe"
        elif sys.platform == 'darwin':
            ffmpegname = u"ffmpeg"
        elif find_executable("avconv"):
            ffmpegname = u"avconv"
        else:
            ffmpegname = u"ffmpeg"

        ffmpegpath = find_executable(ffmpegname)
        if ffmpegpath is None:
            if sys.platform == 'darwin':
                self.sessconfig.set(u'general', u'videoanalyserpath',
                                    u"vlc/ffmpeg")
            elif is_android(strict=True):
                self.sessconfig.set(
                    u'general', u'videoanalyserpath',
                    os.path.join(os.environ['ANDROID_PRIVATE'], 'ffmpeg'))
            else:
                self.sessconfig.set(u'general', u'videoanalyserpath',
                                    ffmpegname)
        else:
            self.sessconfig.set(u'general', u'videoanalyserpath', ffmpegpath)

        # Set videoplayer path
        if sys.platform == 'win32':
            videoplayerpath = os.path.expandvars(
                '${PROGRAMFILES}') + '\\Windows Media Player\\wmplayer.exe'
        elif sys.platform == 'darwin':
            videoplayerpath = find_executable("vlc") or (
                "/Applications/VLC.app"
                if os.path.exists("/Applications/VLC.app") else
                None) or "/Applications/QuickTime Player.app"
        else:
            videoplayerpath = find_executable("vlc") or "vlc"

        self.sessconfig.set(u'video', u'path', videoplayerpath)

        self.sessconfig.set(u'general', u'ipv6_binds_v4',
                            autodetect_socket_style())
Exemple #19
0
 def test_is_android(self):
     if sys.platform.startswith(
             'linux') and 'ANDROID_PRIVATE' in os.environ:
         self.assertTrue(is_android())
     else:
         self.assertFalse(is_android())