예제 #1
0
def processVideo(data, s):
    global messageQue

    millis = str(int(round(time.time() * 1000)))
    uniqueID = f"{''.join([str(random.randint(0, 9)) for i in range(10)])}_{millis}"
    if not os.path.isdir(tmpDir): os.makedirs(tmpDir)

    if data['type'] == 'edit':
        newFile = cleanPath(f"{tmpDir}/{uniqueID}.{data['oldExt']}")
        try:
            with open(newFile, "wb") as f:
                f.write(
                    requests.get(data['url'], allow_redirects=True).content)
        except:
            messageQue += [{
                "channel":
                data["channel"],
                "type":
                "error",
                "message":
                "There was an error while downloading your file."
            }]
            return

        VEB_RESULT = videoEdit(newFile,
                               data['args'],
                               durationUnder=120,
                               logErrors=True)
        if VEB_RESULT[0] == 0:
            if os.path.getsize(VEB_RESULT[1]) < 8 * 1024**2:
                messageQue += [{
                    "channel": data["channel"],
                    "type": "file",
                    "file": VEB_RESULT[1],
                    "message": data["message"]
                }]
            else:
                messageQue += [{
                    "channel":
                    data["channel"],
                    "type":
                    "error",
                    "message":
                    f"Output file is > {8 * 1024 ** 2} Bytes, a solution will be found soon."
                }]
                tryToDeleteFile(VEB_RESULT[1])
                # SWHAP({'type': 'file', 'file': open(VEB_RESULT[1], "rb").read()}, s)
        else:
            msg = "Something went wrong editing your file, sorry." if len(
                VEB_RESULT) < 2 else ("Error: " + VEB_RESULT[1])
            messageQue += [{
                "channel": data["channel"],
                "type": "error",
                "message": msg
            }]
    elif data['type'] == 'download':
        print(f"Download - {data['url']}")
        if download(fileName := f"{tmpDir}/{uniqueID}.mp4",
                    data['url'],
                    duration=110):
예제 #2
0
 def func():
     args2 = args.copy()
     videoEditResult = videoEdit(*args2['args'],
                                 fixPrint=botPrint,
                                 durationUnder=120)
     return [
         videoEditResult[0], newFile, videoEditResult[1:], args2["gid"]
     ]
예제 #3
0
        def func():
            args2 = args.copy()

            if args2['f'] == imageCorrupt:
                imageCorrupt(*args2['args'])
                return [0, os.path.splitext(args2['args'][1])[0] + ".png", args2["gid"]]
            else:
                videoEditResult = videoEdit(*args2['args'], fixPrint = botPrint, durationUnder = 120)
                return [videoEditResult[0], newFile, videoEditResult[1:], args2["gid"]]
예제 #4
0
def getContent(m, ID, tweet, uniquePrefix, reply, isRetweet):
    name = ""
    mediaType = "mp4"

    if tweet._json['extended_entities']['media'][0][
            'type'] == 'animated_gif' or m['expanded_url'].split(
                '/')[-2] == "video":  #Check if GIF or normal video
        name = f"{uniquePrefix}_{ID}.mp4"
        subprocess.check_output([
            "youtube-dl", "--quiet", "--no-playlist", "--geo-bypass",
            "--merge-output-format", "mp4", "-r", "5M", "-o",
            f"{uniquePrefix}_{ID}.mp4", f"{m['expanded_url']}"
        ])
    else:  #Check if image
        mediaType = "png"
        TExt = m['media_url'].split('.')[-1]
        name = f'''{uniquePrefix}_{ID}.{TExt}'''
        if TExt == "jpg":
            mediaType = "png"
        with open(name, 'wb') as f:
            f.write(requests.get(m['media_url']).content)

    tt = reply._json['full_text']
    #print("Tweet text: ", tt)
    txt = re.split("@videoeditbot", tt, flags=re.IGNORECASE)[-1].strip()
    for i in tweet._json['entities']['media']:
        txt = txt.replace(i['url'], "")
    if isRetweet:
        txt = re.sub(r"https:\/\/t.co\/\S{1,30}$", '', txt)
    if 'tovid' in txt.lower():
        mediaType = "mp4"

    j = txt.strip().replace(' ', '').replace('\n', '')

    prefix = f"P-{UFID(ID, 3)}"

    def bpnt(m):
        print(f"{prefix}:\t\t{m}")

    tt = tmpName if (tmpName := '@' + reply._json['user']['screen_name']
                     ) != '@videoeditbot' else ""
    now = datetime.datetime.now()
    millis = str(int(round(time.time() * 1000)))
    folder = DIRECTORY
    foldName = reply._json['user']['screen_name'].lower()
    newFolder = f"{folder}/{foldName}"
    finalName = f"{uniquePrefix}_{ID}.{mediaType}"
    fileName = f"_{foldName}_{millis}_{now.year}-{now.month}-{now.day}-{now.hour}.{now.minute}.{now.second}_{finalName[-6:]}"
    newLocation = f"{newFolder}/{fileName}"
    newURL = f"{BASEURL}/{foldName}/{fileName}?video"

    arguments = None
    if len(j) < 7 and re.match(r"i\|[0-9]{1,3}", j):
        ret = imageCorrupt(name, j.split('|')[-1])
    else:

        def altPrint(*args, **kwargs):
            botPrint(*args, prefix=prefix, **kwargs)

        isRandom = re.sub(r"@[^ ]{1,}", '',
                          txt).strip() in ['random', 'r', 'rnadom', '']
        ret = videoEdit(name,
                        txt,
                        disallowTimecodeBreak=True,
                        fixPrint=altPrint,
                        durationUnder=120,
                        allowRandom=isRandom)
        if ret == -1:
            bpnt("Not a tweet with arguments, ignoring.")
            if os.path.isfile(finalName):  #Delete downloaded file
                os.remove(finalName)
            return

    #Codes:
    # -1: could not tweet text based reply
    # 0 : told the user that there was an error
    # 1 : send text based reply with link, but reasoning was not handled (ex. duration, aspect ratio, etc.)
    # 2 : sucessfully uploaded video to twitter

    def backup():
        thumbFold = f"{newFolder}/thumb"
        if os.path.isdir(thumbFold) is not True:
            os.makedirs(thumbFold)
        shutil.move(finalName, newLocation)
        if mediaType == "mp4":
            thumbLoc = f"{thumbFold}/{os.path.splitext(fileName)[0]}.jpg"
            os.system(
                f"ffmpeg -hide_banner -loglevel fatal -i '{newLocation}' -vframes 1 '{thumbLoc}'"
            )
            img = Image.open(thumbLoc)
            img.thumbnail((250, 250))
            img.save(thumbLoc)

    replyApi = api  #random.choice(apilist)

    #Respond if error code in destroyer result
    try:
        code = ret[0]
        if code > 0:
            if os.path.isfile(
                    finalName):  #If the file is still there, remove it
                os.remove(finalName)
            if len(ret) > 1:
                responce = ret[1]
            else:
                responce = "Unhandled error."
            replyApi.update_status(
                f"{tt} Sorry, something went wrong editing your video. Error: {responce}",
                in_reply_to_status_id=str(reply.id),
                auto_populate_reply_metadata=True)
            bpnt("Tweet posted (0) (Handled)")
            return
    except Exception as e:
        if (tc := testCode(e)):
            bpnt(tc)
            return
        bpnt(e)