示例#1
0
    def __DownloadNfoParseFormatType(self, releaseInfo, description):
        if releaseInfo.IsCodecSet():
            releaseInfo.Logger.info(
                "Codec '%s' is already set, not getting from the torrent page."
                % releaseInfo.Codec)
            return

        # <tr><td class="heading" align="right" valign="top">Rip Specs</td><td colspan="2" align="left" valign="top">[General] Format: AVI
        # ...
        # </td></tr>
        ripSpecs = re.search(
            r"<tr><td.*?>Rip Specs</td><td.*?>(.+?)</td></tr>", description,
            re.DOTALL)
        if ripSpecs is None:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Rip specifications can't be found on the page.")

        ripSpecs = ripSpecs.group(1).upper()

        if ripSpecs.find("DVD FORMAT:") >= 0:
            self.__DownloadNfoParseDvdImage(releaseInfo, ripSpecs)
        elif ripSpecs.find("XVID") >= 0:
            releaseInfo.Codec = "XviD"
        elif ripSpecs.find("DIVX") >= 0:
            releaseInfo.Codec = "DivX"
        elif ripSpecs.find("X264") >= 0 or ripSpecs.find(
                "V_MPEG4/ISO/AVC") >= 0:
            releaseInfo.Codec = "x264"
        else:
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "Can't figure out codec from the rip specifications.")
示例#2
0
    def __GetMediaInfoContainer(self, mediaInfo):
        container = ""

        if mediaInfo.IsAvi():
            container = "AVI"
        elif mediaInfo.IsMkv():
            container = "MKV"
        elif mediaInfo.IsMp4():
            container = "MP4"
        elif mediaInfo.IsVob():
            container = "VOB IFO"

        if self.ReleaseInfo.IsContainerSet():
            if container != self.ReleaseInfo.Container:
                if self.ReleaseInfo.IsForceUpload():
                    self.ReleaseInfo.Logger.info(
                        "Container is set to '%s', detected MediaInfo container is '%s' ('%s'). Ignoring mismatch because of force upload."
                        % (self.ReleaseInfo.Container, container,
                           mediaInfo.Container))
                else:
                    raise PtpUploaderException(
                        "Container is set to '%s', detected MediaInfo container is '%s' ('%s')."
                        % (self.ReleaseInfo.Container, container,
                           mediaInfo.Container))
        else:
            if len(container) > 0:
                self.ReleaseInfo.Container = container
            else:
                raise PtpUploaderException("Unsupported container: '%s'." %
                                           mediaInfo.Container)
示例#3
0
    def __DownloadNfoParseResolution(self, releaseInfo, description):
        if releaseInfo.IsResolutionTypeSet():
            releaseInfo.Logger.info(
                "Resolution type '%s' is already set, not getting from the torrent page."
                % releaseInfo.ResolutionType)
            return

        if description.find('"genreimages/hdrip720.png"') != -1:
            releaseInfo.ResolutionType = "720"
        elif description.find('"genreimages/hdrip1080.png"') != -1:
            releaseInfo.ResolutionType = "1080"
        elif description.find('"genreimages/bluray.png"') != -1:
            raise PtpUploaderException(JobRunningState.Ignored_NotSupported,
                                       "Untouched Blu-ray aren't supported.")
        else:
            # Other HD is in the genre list. It's not supported.
            # <td style="border:none;"><img src="genreimages/dvdr.png" width="40" height="40" border="0" title="DVDR"></td>
            matches = re.search(
                """<td.*?><img src="genreimages/.+?" .*?title="(.+?)".*?></td>""",
                description)
            if matches is not None:
                notSupportedType = matches.group(1).lower()
                if notSupportedType == "hd":
                    raise PtpUploaderException(
                        JobRunningState.Ignored_NotSupported,
                        "Unsupported source or resolution type '%s'." %
                        notSupportedType)

            releaseInfo.ResolutionType = "Other"
示例#4
0
    def UploadMovie(logger, releaseInfo, torrentPath, releaseDescription):
        url = ""
        paramList = Ptp.__UploadMovieGetParamsCommon(releaseInfo,
                                                     releaseDescription)

        # We always use HTTPS for uploading because if "Force HTTPS" is enabled in the profile then the HTTP upload is not working.
        if releaseInfo.HasPtpId():
            logger.info(
                "Uploading torrent '%s' to PTP as a new format for 'https://tls.passthepopcorn.me/torrents.php?id=%s'."
                % (torrentPath, releaseInfo.PtpId))
            url = "https://tls.passthepopcorn.me/upload.php?groupid=%s" % releaseInfo.PtpId
            paramList.update(
                Ptp.__UploadMovieGetParamsForAddFormat(releaseInfo.PtpId))
        else:
            logger.info("Uploading torrent '%s' to PTP as a new movie." %
                        torrentPath)
            url = "https://tls.passthepopcorn.me/upload.php"
            paramList.update(
                Ptp.__UploadMovieGetParamsForNewMovie(releaseInfo))

        # Add the torrent file.
        torrentFilename = os.path.basename(torrentPath)
        # Filename without path.
        files = {
            "file_input":
            (torrentFilename, open(torrentPath,
                                   "rb"), "application/x-bittorent")
        }
        result = MyGlobals.session.post(url, data=paramList, files=files)
        response = result.text
        Ptp.CheckIfLoggedInFromResponse(result, response)

        # If the repsonse contains our announce url then we are on the upload page and the upload wasn't successful.
        if response.find(Settings.PtpAnnounceUrl) != -1:
            # Get the error message.
            # <div class="alert alert--error text--center">No torrent file uploaded, or file is empty.</div>
            errorMessage = ""
            match = re.search(
                r"""<div class="alert alert--error.*?>(.+?)</div>""", response)
            if match is not None:
                errorMessage = match.group(1)

            raise PtpUploaderException(
                "Upload to PTP failed: '%s' (%s). (We are still on the upload page.)"
                % (errorMessage, result.status_code))

        # URL format in case of successful upload: https://tls.passthepopcorn.me/torrents.php?id=9329&torrentid=91868
        match = re.match(
            r".*?passthepopcorn\.me/torrents\.php\?id=(\d+)&torrentid=(\d+)",
            result.url)
        if match is None:
            raise PtpUploaderException(
                "Upload to PTP failed: result URL '%s' (%s) is not the expected one."
                % (result.url, result.status_code))

        ptpId = match.group(1)
        releaseInfo.PtpTorrentId = match.group(2)

        if not releaseInfo.HasPtpId():
            releaseInfo.PtpId = ptpId
示例#5
0
    def __HandleAutoCreatedJob(self, logger, releaseInfo):
        releaseInfo.ReleaseName = self.__RestoreReleaseName(
            releaseInfo.ReleaseName)

        # In case of automatic announcement we have to check the release name if it is valid.
        # We know the release name from the announcement, so we can filter it without downloading anything (yet) from the source.
        releaseNameParser = ReleaseNameParser(releaseInfo.ReleaseName)
        isAllowedMessage = releaseNameParser.IsAllowed()
        if isAllowedMessage is not None:
            raise PtpUploaderException(JobRunningState.Ignored,
                                       isAllowedMessage)

        releaseNameParser.GetSourceAndFormat(releaseInfo)

        releaseName, releaseInfo.Size = self.__GetReleaseNameAndSize(
            logger, releaseInfo)
        if releaseName != releaseInfo.ReleaseName:
            raise PtpUploaderException(
                "Announcement release name '%s' and release name '%s' on torrent page are different."
                % (releaseInfo.ReleaseName, releaseName))

        # Pretime is not indicated on TorrentLeech so we have to rely on our scene groups list.
        if releaseNameParser.Scene:
            releaseInfo.SetSceneRelease()

        if (not releaseInfo.IsSceneRelease()
            ) and self.AutomaticJobFilter == "SceneOnly":
            raise PtpUploaderException(JobRunningState.Ignored,
                                       "Non-scene release.")

        self.__ReadImdbIdFromNfoPage(logger, releaseInfo)
示例#6
0
    def __DownloadNfoParseSourceType(self, releaseInfo, description):
        if releaseInfo.IsSourceSet():
            releaseInfo.Logger.info(
                "Source '%s' is already set, not getting from the torrent page."
                % releaseInfo.Source)
            return

        # <tr><td class="heading" align="right" valign="top">Source</td><td colspan="2" align="left" valign="top">dvdrip</td></tr>
        matches = re.search(
            """<tr><td class="heading".*?>Source</td><td.*?>(.+?)</td></tr>""",
            description)
        if matches is None:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Source type can't be found. Probably the layout of the site has changed."
            )

        sourceType = matches.group(1).lower()

        if sourceType == "blu-ray":
            releaseInfo.Source = "Blu-ray"
        elif sourceType == "dvd":
            releaseInfo.Source = "DVD"
        elif sourceType == "web":
            releaseInfo.Source = "WEB"
        elif sourceType == "vhs":
            releaseInfo.Source = "VHS"
        elif sourceType == "tv":
            releaseInfo.Source = "TV"
        else:
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "Unsupported source type '%s'." % sourceType)
    def __CheckImdbRatingAndVoteCount(self):
        # Only applies to automatically created jobs.
        if self.ReleaseInfo.IsUserCreatedJob():
            return

        if not self.__IsAllowedImdbRating():
            raise PtpUploaderException("Ignored because of IMDb rating: %s." %
                                       (self.ReleaseInfo.ImdbRating))

        if not self.__IsAllowedImdbVoteCount():
            raise PtpUploaderException(
                "Ignored because of IMDb vote count: %s." %
                (self.ReleaseInfo.ImdbVoteCount))
    def __GetMediaInfoHandleDvdImage(self):
        # Get all IFOs.
        ifos = []
        for file in self.AdditionalFiles:
            if file.lower().endswith(".ifo"):
                mediaInfo = MediaInfo(self.ReleaseInfo.Logger, file,
                                      self.ReleaseInfo.GetReleaseUploadPath())
                ifos.append(mediaInfo)

        # Sort them by duration.
        sortedIfos = []
        for ifo in ifos:
            item = ifo.DurationInSec, ifo  # Add as a tuple.
            sortedIfos.append(item)

        sortedIfos.sort(reverse=True)

        # Use the longest.
        ifo = sortedIfos[0][1]
        if ifo.DurationInSec <= 0:
            raise PtpUploaderException(
                "None of the IFOs have duration. MediaInfo is probably too old."
            )

        ifoPathLower = ifo.Path.lower()
        if not ifoPathLower.endswith("_0.ifo"):
            raise PtpUploaderException(
                "Unsupported VIDEO_TS layout. The longest IFO is '%s' with duration '%s'."
                % (ifo.Path, ifo.DurationInSec))

        # Get the next VOB.
        # (This could be a simple replace but Linux's filesystem is case-sensitive...)
        vobPath = None
        ifoPathLower = ifoPathLower.replace("_0.ifo", "_1.vob")
        for file in self.VideoFiles:
            if file.lower() == ifoPathLower:
                vobPath = file
                break

        if vobPath is None:
            raise PtpUploaderException(
                "Unsupported VIDEO_TS layout. Can't find the next VOB for IFO '%s'."
                % ifo.Path)

        vobMediaInfo = MediaInfo(self.ReleaseInfo.Logger, vobPath,
                                 self.ReleaseInfo.GetReleaseUploadPath())
        self.MainMediaInfo = vobMediaInfo
        self.VideoEntries.append(
            ReleaseDescriptionVideoEntry(ifo, numberOfScreenshotsToTake=0))
        self.VideoEntries.append(ReleaseDescriptionVideoEntry(vobMediaInfo))
    def __FillOutDetailsForNewMovieByExternalSources(self):
        if self.ReleaseInfo.HasPtpId() or self.ReleaseInfo.IsZeroImdbId():
            return

        imdbInfo = Imdb.GetInfo(self.ReleaseInfo.Logger,
                                self.ReleaseInfo.GetImdbId())

        # Ignore series (if force upload is not set).
        if imdbInfo.IsSeries:
            if self.ReleaseInfo.IsForceUpload():
                self.ReleaseInfo.Logger.info(
                    "The release is a series, but continuing due to force upload."
                )
            else:
                raise PtpUploaderException(JobRunningState.Ignored_Forbidden,
                                           "It is a series.")

        # PTP returns with the original title, IMDb's iPhone API returns with the international English title.
        self.ReleaseInfo.InternationalTitle = imdbInfo.Title
        if self.ReleaseInfo.Title != self.ReleaseInfo.InternationalTitle and len(
                self.ReleaseInfo.InternationalTitle
        ) > 0 and self.ReleaseInfo.Title.find(" AKA ") == -1:
            self.ReleaseInfo.Title += " AKA " + self.ReleaseInfo.InternationalTitle

        if len(self.ReleaseInfo.MovieDescription) <= 0:
            self.ReleaseInfo.MovieDescription = imdbInfo.Plot

        if not self.ReleaseInfo.IsCoverArtUrlSet():
            self.ReleaseInfo.CoverArtUrl = imdbInfo.PosterUrl
            if not self.ReleaseInfo.IsCoverArtUrlSet():
                self.ReleaseInfo.CoverArtUrl = MoviePoster.Get(
                    self.ReleaseInfo.Logger, self.ReleaseInfo.GetImdbId())

        self.ReleaseInfo.ImdbRating = imdbInfo.ImdbRating
        self.ReleaseInfo.ImdbVoteCount = imdbInfo.ImdbVoteCount
示例#10
0
 def __AddOne(self, ptpSubtitleId, languageName):
     languageName = languageName.lower()
     if self.List.get(languageName) is None:
         self.List[languageName] = ptpSubtitleId
     else:
         raise PtpUploaderException("Text '%s' is not unique!" %
                                    languageName)
示例#11
0
    def GetMoviePageOnPtpByImdbId(logger, imdbId):
        logger.info("Trying to find movie with IMDb id '%s' on PTP." % imdbId)

        result = MyGlobals.session.get(
            "https://tls.passthepopcorn.me/torrents.php?imdb=%s&json=1" %
            Ptp.NormalizeImdbIdForPtp(imdbId))
        response = result.text
        Ptp.CheckIfLoggedInFromResponse(result, response)

        # If there is a movie: result.url = https://tls.passthepopcorn.me/torrents.php?id=28577
        # If there is no movie: result.url = https://tls.passthepopcorn.me/torrents.php?imdb=1535492
        match = re.match(r".*?passthepopcorn\.me/torrents\.php\?id=(\d+)",
                         result.url)
        if match is not None:
            ptpId = match.group(1)
            url = result.url
            url = url.replace("&json=1", "")
            logger.info("Movie with IMDb id '%s' exists on PTP at '%s'." %
                        (imdbId, url))
            return PtpMovieSearchResult(ptpId, response)
        elif response.find(
                "<h2>Error 404</h2>"
        ) != -1:  # For some deleted movies PTP return with this error.
            logger.info(
                "Movie with IMDb id '%s' doesn't exists on PTP. (Got error 404.)"
                % imdbId)
            return PtpMovieSearchResult(ptpId="", moviePageJsonText=None)
        elif response.find(
                "<h2>Your search did not match anything.</h2>") != -1:
            logger.info("Movie with IMDb id '%s' doesn't exists on PTP." %
                        imdbId)
            return PtpMovieSearchResult(ptpId="", moviePageJsonText=None)
        else:  # Multiple movies with the same IMDb id.
            raise PtpUploaderException(
                "There are multiple movies on PTP with IMDb id '%s'." % imdbId)
示例#12
0
    def __GetReleaseNameAndSize(self, logger, releaseInfo):
        url = "https://www.torrentleech.org/torrent/%s" % releaseInfo.AnnouncementId
        logger.info("Downloading release name and size from page '%s'." % url)

        result = MyGlobals.session.get(url)
        result.raise_for_status()
        response = result.text
        self.__CheckIfLoggedInFromResponse(response)

        # Get release name.
        matches = re.search(
            "<title>Torrent Details for (.+) :: TorrentLeech.org</title>",
            response)
        if matches is None:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Release name can't be found on torrent page.")
        releaseName = DecodeHtmlEntities(matches.group(1))
        releaseName = self.__RestoreReleaseName(releaseName)

        # Get size.
        # <td class="label">Size</td><td>5.47 GB</td></tr>
        size = 0
        matches = re.search(
            r"""<td class="label">Size</td><td>(.+)</td></tr>""", response)
        if matches is None:
            logger.warning("Size not found on torrent page.")
        else:
            size = GetSizeFromText(matches.group(1))

        return releaseName, size
示例#13
0
文件: Ptp.py 项目: Aniverse/p1
	def NormalizeImdbIdForPtp(imdbId):
		if len( imdbId ) < 7:
			return imdbId.rjust( 7, '0' )
		elif len( imdbId ) > 7:
			raise PtpUploaderException( "IMDb ID '%s' is longer than seven characters." % imdbId )
		else:
			return imdbId
示例#14
0
    def __CheckIfExistsOnPtp(self):
        # TODO: this is temporary here. We should support it everywhere.
        # If we are not logged in here that could mean that the download took a lot of time and the user got logged out for some reason.
        Ptp.Login()

        # This could be before the Ptp.Login() line, but this way we can hopefully avoid some logging out errors.
        if self.ReleaseInfo.IsZeroImdbId():
            self.ReleaseInfo.Logger.info(
                "IMDb ID is set zero, ignoring the check for existing release."
            )
            return

        movieOnPtpResult = None

        if self.ReleaseInfo.HasPtpId():
            movieOnPtpResult = Ptp.GetMoviePageOnPtp(
                self.ReleaseInfo.Logger, self.ReleaseInfo.GetPtpId())
        else:
            movieOnPtpResult = Ptp.GetMoviePageOnPtpByImdbId(
                self.ReleaseInfo.Logger, self.ReleaseInfo.GetImdbId())
            self.ReleaseInfo.PtpId = movieOnPtpResult.PtpId

        # Check (again) if is it already on PTP.
        existingRelease = movieOnPtpResult.IsReleaseExists(self.ReleaseInfo)
        if existingRelease is not None:
            raise PtpUploaderException(
                JobRunningState.DownloadedAlreadyExists,
                "Got uploaded to PTP while we were working on it. Skipping upload because of format '%s'."
                % existingRelease)
示例#15
0
 def GetTitle(self):
     self.__LoadmdbInfo()
     title = self.JsonMovie["title"]
     if (title is None) or len(title) == 0:
         raise PtpUploaderException(
             "Bad PTP movie info JSON response: title is empty.\nFull response:\n%s"
             % self.JsonResponse)
     return title
示例#16
0
 def GetYear(self):
     self.__LoadmdbInfo()
     year = self.JsonMovie["year"]
     if (year is None) or len(year) == 0:
         raise PtpUploaderException(
             "Bad PTP movie info JSON response: year is empty.\nFull response:\n%s"
             % self.JsonResponse)
     return year
示例#17
0
 def GetTags(self):
     self.__LoadmdbInfo()
     tags = self.JsonMovie["tags"]
     if tags is None:
         raise PtpUploaderException(
             "Bad PTP movie info JSON response: tags key doesn't exists.\nFull response:\n%s"
             % self.JsonResponse)
     return tags
示例#18
0
 def __HandleAutoCreatedJob(self, releaseInfo):
     if releaseInfo.IsDvdImage():
         if not self.AutoUploadDvdImage:
             raise PtpUploaderException(
                 JobRunningState.Ignored,
                 "DVD image is on your ignore list.")
     elif releaseInfo.ResolutionType == "720":
         if not self.AutoUpload720p:
             raise PtpUploaderException(JobRunningState.Ignored,
                                        "720p is on your ignore list.")
     elif releaseInfo.ResolutionType == "1080":
         if not self.AutoUpload1080p:
             raise PtpUploaderException(JobRunningState.Ignored,
                                        "1080p is on your ignore list.")
     elif releaseInfo.ResolutionType == "Other":
         if not self.AutoUploadSd:
             raise PtpUploaderException(JobRunningState.Ignored,
                                        "SD is on your ignore list.")
    def __CheckAnnouncementSource(self):
        self.ReleaseInfo.Logger.info(
            u"Working on announcement from '%s' with id '%s' and name '%s'." %
            (self.ReleaseInfo.AnnouncementSourceName,
             self.ReleaseInfo.AnnouncementId, self.ReleaseInfo.ReleaseName))

        self.ReleaseInfo.JobStartTimeUtc = datetime.datetime.utcnow()
        self.ReleaseInfo.JobRunningState = JobRunningState.InProgress
        self.ReleaseInfo.ErrorMessage = ""
        Database.DbSession.commit()

        if self.ReleaseInfo.AnnouncementSource is None:
            raise PtpUploaderException("Announcement source '%s' is unknown." %
                                       self.ReleaseInfo.AnnouncementSourceName)

        if not self.ReleaseInfo.AnnouncementSource.IsEnabled():
            raise PtpUploaderException(
                "Announcement source '%s' is disabled." %
                self.ReleaseInfo.AnnouncementSourceName)
示例#20
0
文件: Ptp.py 项目: Aniverse/p1
	def GetMoviePageOnPtp(logger, ptpId):
		logger.info( "Getting movie page for PTP id '%s'." % ptpId )
		
		result = MyGlobals.session.get( "https://passthepopcorn.me/torrents.php?id=%s&json=1" % ptpId )
		response = result.text
		Ptp.CheckIfLoggedInFromResponse( result, response )

		if response.find( "<h2>Error 404</h2>" ) != -1:
			raise PtpUploaderException( "Movie with PTP id '%s' doesn't exists." % ptpId )

		return PtpMovieSearchResult( ptpId, response )
示例#21
0
    def __CheckIfLoggedInFromResponse(self, response):
        if response.find('<div class="recaptcha">') != -1:
            raise PtpUploaderInvalidLoginException(
                "Can't login to TorrentLeech because there is a captcha on the login page."
            )

        if response.find(
                '<form method="post" action="/user/account/login/">') != -1:
            raise PtpUploaderException(
                "Looks like you are not logged in to TorrentLeech. Probably due to the bad user name or password in settings."
            )
示例#22
0
    def MarkAsDvdImageIfNeeded(self, releaseInfo):
        for file in self.AdditionalFiles:
            if file.lower().endswith(".ifo"):
                releaseInfo.Codec = "DVD5"
                # Make sure that ReleaseDescriptionFormatter will recognize this as a DVD image.
                if not releaseInfo.IsDvdImage():
                    raise PtpUploaderException(
                        "Codec is set to DVD5, yet release info says that this is not a DVD image."
                    )

                return
示例#23
0
    def __DownloadNfoParseDvdImage(releaseInfo, ripSpecs):
        if ripSpecs.find("DVD FORMAT: NTSC") >= 0:
            releaseInfo.ResolutionType = "NTSC"
        elif ripSpecs.find("DVD FORMAT: PAL") >= 0:
            releaseInfo.ResolutionType = "PAL"
        else:
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "Can't figure out DVD resolution type from the rip specifications."
            )

        if ripSpecs.find("VIDEO: ") < 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "DVD video info can't be found in the rip specifications.")

        if ripSpecs.find("AUDIO: ") < 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "DVD audio info can't be found in the rip specifications.")

        if ripSpecs.find( "VIDEO: UNTOUCHED" ) < 0 \
         or ripSpecs.find( "AUDIO: UNTOUCHED" ) < 0 \
         or ( ripSpecs.find( "MENUS: " ) >= 0 and ripSpecs.find( "MENUS: UNTOUCHED" ) < 0 ) \
         or ( ripSpecs.find( "DVD EXTRAS: " ) >= 0 and ripSpecs.find( "DVD EXTRAS: UNTOUCHED" ) < 0 ):
            raise PtpUploaderException(JobRunningState.Ignored_NotSupported,
                                       "The DVD is not untouched.")

        if releaseInfo.Size <= 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "Size not set, can't detect DVD's size.")

        # TODO: this isn't correct for multi disc torrents. It must be detected from the file list.
        if releaseInfo.Size > 4707319808:
            releaseInfo.Codec = "DVD9"
        else:
            releaseInfo.Codec = "DVD5"

        releaseInfo.Container = "VOB IFO"
示例#24
0
def RemoveDisallowedCharactersFromPath(text):
    newText = text

    # These characters can't be in filenames on Windows.
    forbiddenCharacters = r"""\/:*?"<>|"""
    for c in forbiddenCharacters:
        newText = newText.replace(c, "")

    newText = newText.strip()

    if len(newText) > 0:
        return newText
    else:
        raise PtpUploaderException(
            "New name for '%s' resulted in empty string." % text)
示例#25
0
	def __GetMediaInfoResolution(self, mediaInfo):
		resolution = ""

		# Indicate the exact resolution for standard definition releases.
		# It is not needed for DVD images.
		if self.ReleaseInfo.IsStandardDefinition() and ( not self.ReleaseInfo.IsDvdImage() ):
			resolution = "%sx%s" % ( mediaInfo.Width, mediaInfo.Height )
			
		if len( self.ReleaseInfo.Resolution ) > 0:
			if resolution != self.ReleaseInfo.Resolution:
				if self.ReleaseInfo.IsForceUpload():
					self.ReleaseInfo.Logger.info( "Resolution is set to '%s', detected MediaInfo resolution is '%s' ('%sx%s'). Ignoring mismatch because of force upload." % ( self.ReleaseInfo.Resolution, resolution, mediaInfo.Width, mediaInfo.Height ) )
				else:
					raise PtpUploaderException( "Resolution is set to '%s', detected MediaInfo resolution is '%s' ('%sx%s')." % ( self.ReleaseInfo.Resolution, resolution, mediaInfo.Width, mediaInfo.Height ) )
		else:
			self.ReleaseInfo.Resolution = resolution
    def __ValidateReleaseInfo(self):
        # Make sure we have IMDb or PTP id.
        if (not self.ReleaseInfo.HasImdbId()) and (
                not self.ReleaseInfo.HasPtpId()):
            raise PtpUploaderException(JobRunningState.Ignored_MissingInfo,
                                       "IMDb or PTP id must be specified.")

        # Make sure the source is providing a name.
        self.ReleaseInfo.ReleaseName = self.ReleaseInfo.ReleaseName.strip()
        if len(self.ReleaseInfo.ReleaseName) <= 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Name of the release is not specified.")

        # Make sure the source is providing release source information.
        if len(self.ReleaseInfo.Source) <= 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Source of the release is not specified.")

        # Make sure the source is providing release codec information.
        if len(self.ReleaseInfo.Codec) <= 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Codec of the release is not specified.")

        # Make sure the source is providing release resolution type information.
        if len(self.ReleaseInfo.ResolutionType) <= 0:
            raise PtpUploaderException(
                JobRunningState.Ignored_MissingInfo,
                "Resolution type of the release is not specified.")

        # HD XviDs are not allowed.
        if self.ReleaseInfo.IsHighDefinition() and (
                self.ReleaseInfo.Codec == "XviD"
                or self.ReleaseInfo.Codec == "DivX"):
            raise PtpUploaderException(JobRunningState.Ignored_Forbidden,
                                       "HD XviDs and DivXs are not allowed.")

        # We only support VOB IFO container for DVD images.
        if self.ReleaseInfo.IsDvdImage(
        ) and self.ReleaseInfo.Container != "VOB IFO":
            raise PtpUploaderException(
                JobRunningState.Ignored_NotSupported,
                "Only VOB IFO container is supported for DVD images.")
示例#27
0
    def __GetMediaInfoCodec(self, mediaInfo):
        codec = ""

        if mediaInfo.IsX264():
            codec = "x264"
            if mediaInfo.IsAvi():
                raise PtpUploaderException("X264 in AVI is not allowed.")
        elif mediaInfo.IsH264():
            codec = "H.264"
            if mediaInfo.IsAvi():
                raise PtpUploaderException("H.264 in AVI is not allowed.")
        elif mediaInfo.IsXvid():
            codec = "XviD"
            if mediaInfo.IsMkv():
                raise PtpUploaderException("XviD in MKV is not allowed.")
        elif mediaInfo.IsDivx():
            codec = "DivX"
            if mediaInfo.IsMkv():
                raise PtpUploaderException("DivX in MKV is not allowed.")
        elif mediaInfo.IsVc1():
            codec = "VC-1"
        elif mediaInfo.IsMpeg2Codec():
            codec = "MPEG-2"
        elif self.ReleaseInfo.IsDvdImage():
            # Codec type DVD5 and DVD9 can't be figured out from MediaInfo.
            codec = self.ReleaseInfo.Codec

        if self.ReleaseInfo.IsCodecSet():
            if codec != self.ReleaseInfo.Codec:
                if Upload.__CanIgnoreDetectedAndSetCodecDifference(
                        codec, self.ReleaseInfo.Codec):
                    self.ReleaseInfo.Logger.info(
                        "Codec is set to '%s', detected MediaInfo codec is '%s' ('%s'). Using the detected codec."
                        % (self.ReleaseInfo.Codec, codec, mediaInfo.Codec))
                    self.ReleaseInfo.Codec = codec
                elif self.ReleaseInfo.IsForceUpload():
                    self.ReleaseInfo.Logger.info(
                        "Codec is set to '%s', detected MediaInfo codec is '%s' ('%s'). Ignoring mismatch because of force upload."
                        % (self.ReleaseInfo.Codec, codec, mediaInfo.Codec))
                else:
                    raise PtpUploaderException(
                        "Codec is set to '%s', detected MediaInfo codec is '%s' ('%s')."
                        % (self.ReleaseInfo.Codec, codec, mediaInfo.Codec))
        else:
            if len(codec) > 0:
                self.ReleaseInfo.Codec = codec
            else:
                raise PtpUploaderException("Unsupported codec: '%s'." %
                                           mediaInfo.Codec)
    def __CreateReleaseDirectory(self):
        if self.ReleaseInfo.IsJobPhaseFinished(
                FinishedJobPhase.Download_CreateReleaseDirectory):
            self.ReleaseInfo.Logger.info(
                u"Release root path creation phase has been reached previously, not creating it again."
            )
            return

        releaseRootPath = self.ReleaseInfo.GetReleaseRootPath()
        self.ReleaseInfo.Logger.info(
            u"Creating release root directory at '%s'." % releaseRootPath)

        if os.path.exists(releaseRootPath):
            raise PtpUploaderException(
                u"Release root directory '%s' already exists." %
                releaseRootPath)

        os.makedirs(releaseRootPath)

        self.ReleaseInfo.SetJobPhaseFinished(
            FinishedJobPhase.Download_CreateReleaseDirectory)
        Database.DbSession.commit()
示例#29
0
    def GetCoverArtUrl(self):
        self.__LoadmdbInfo()
        coverArtUrl = self.JsonMovie["art"]
        if coverArtUrl is None:
            raise PtpUploaderException(
                "Bad PTP movie info JSON response: art key doesn't exists.\nFull response:\n%s"
                % self.JsonResponse)

        # It may be false... Eg.: "art": false
        if isinstance(coverArtUrl, basestring):
            # Maximize height in 768 pixels.
            # Example links:
            # http://ia.media-imdb.com/images/M/MV5BMTM2MjE0NTcwNl5BMl5BanBnXkFtZTcwOTM0MDQ1NA@@._V1._SY317_CR1,0,214,317_.jpg
            # http://ia.media-imdb.com/images/M/MV5BMjEwNjQ5NDU4OF5BMl5BanBnXkFtZTYwOTI2NzA5._V1._SY317_CR1,0,214,317_.jpg
            # http://ia.media-imdb.com/images/M/MV5BMzE3NTMwOTk5OF5BMl5BanBnXkFtZTgwODcxNTE1NDE@._V1_UX182_CR0,0,182,268_AL_.jpg
            match = re.match(r"""(.+?\._V1).*\.jpg""", coverArtUrl)
            if match is None:
                return coverArtUrl
            else:
                return match.group(1) + "_SY768_.jpg"
        else:
            return ""
示例#30
0
    def __LoadmdbInfo(self):
        # Already loaded
        if self.JsonMovie is not None:
            return

        # Get IMDb info through PTP's ajax API used by the site when the user presses the auto fill button.
        result = MyGlobals.session.get(
            "https://passthepopcorn.me/ajax.php?action=torrent_info&imdb=%s" %
            Ptp.NormalizeImdbIdForPtp(self.ImdbId))
        self.JsonResponse = result.text
        Ptp.CheckIfLoggedInFromResponse(result, self.JsonResponse)

        # The response is JSON.
        # [{"title":"Devil's Playground","plot":"As the world succumbs to a zombie apocalypse, Cole a hardened mercenary, is chasing the one person who can provide a cure. Not only to the plague but to Cole's own incumbent destiny. DEVIL'S PLAYGROUND is a cutting edge British horror film that features zombies portrayed by free runners for a terrifyingly authentic representation of the undead","art":false,"year":"2010","director":[{"imdb":"1654324","name":"Mark McQueen","role":null}],"tags":"action, horror","writers":[{"imdb":"1057010","name":"Bart Ruspoli","role":" screenplay"}]}]

        jsonResult = json.loads(self.JsonResponse)
        if len(jsonResult) != 1:
            raise PtpUploaderException(
                "Bad PTP movie info JSON response: array length is not one.\nFull response:\n%s"
                % self.JsonResponse)

        self.JsonMovie = jsonResult[0]