TwentyPenguins
TwentyPenguins

Reputation: 83

Convert Windows UNC path to QUrl for Mac

Background: I've got a database where paths to video files are stored as Windows UNC path strings, for example "\\11.22.33.44\path\movie.mp4". (The Windows format is a legacy thing and I can't fundamentally change how these are stored).

I'm now working on a Python media player using PyQt5's QMediaPlayer. On Windows, it's working fine, and:

self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(str(fileName))))

opens up the movie file in the player.

However there's a requirement to make this work on Mac as well, and I'm hitting problems getting the Windows UNC path into a QUrl format that works on Mac. I've tried various os.path and pathlib examples online, but none of them seem to create a valid path that QUrl.fromLocalFile will work with. I'm always hitting Error: Failed to load media. I'm getting results like "/11.22.33.44/file/movie.mp4" where there's both a backslash and a foreslash at the start, things like that.

I should point out that yes these are network paths, being sent to a method called 'fromLocalFile', but the documentation for QUrl does state that it will work with network paths: https://doc.qt.io/qt-5/qurl.html#fromLocalFile- so I don't think that should be the issue?

Can somebody please explain to me the proper way to make this work? I assume Pathlib should be able to use this and I'm just approaching it the wrong way.

(This question is NOT a duplicate of Loading video using QMediaPlayer and UNC paths because my code IS working on Windows and I'm having a different problem with Mac-friendly paths.)

Upvotes: 1

Views: 988

Answers (1)

ekhumoro
ekhumoro

Reputation: 120598

I doubt whether there's a completely reliable and portable way to do this for an arbitrary network path. However, assuming your Windows UNC paths are always in the same format, something like this should work:

import platform
from PyQt5.QtCore import QUrl

def make_url(unc):
    if platform.system() == 'Windows':
        url = QUrl.fromLocalFile(unc)
    else:
        url = QUrl(unc.replace('\\', '/'))
        if platform.system() == 'Darwin':
            url.setScheme('smb')
    return url

print(make_url(r'\\11.22.33.44\path\movie.mp4'))

Or if that doesn't work, try:

def make_url(unc):
    if platform.system() != 'Windows':
        unc = unc.replace('\\', '/')
    return QUrl.fromLocalFile(unc)   

(NB: I am on Linux, so I have no way of testing this).

Upvotes: 1

Related Questions