예제 #1
0
def timer():
    # last_time = datetime.min
    last_time = util.get_current_time()
    while True:
        time.sleep(0.5)
        now = util.get_current_time()
        if last_time.minute != now.minute:
            minute = (60 * now.hour) + now.minute
            new_day = now.day != last_time.day
            last_time = now
            minutely(minute, new_day)
예제 #2
0
def upcoming(request):
    remove = "remove" in request.path

    if remove:
        delete_id = request.GET.get('id')
        if delete_id is not None:
            Post.objects.filter(id=delete_id).delete(
            )  # If it doesn't exist this will just continue
            return redirect('delete_post')

    now = util.get_current_time()
    current_minute = (60 * now.hour) + now.minute
    regenerate = request.GET.get('regenerate')
    if regenerate is not None and regenerate:
        main.generate_queue(current_minute)
        return redirect('upcoming')

    upcoming_posts = Post.objects.filter(posted=False).order_by('post_minute')
    for post in upcoming_posts:
        diff = post.post_minute - current_minute
        if diff > 0:
            hours = diff // 60
            minutes = diff % 60
            post.time_remaining = "{:0>2d}:{:0>2d}".format(hours, minutes)
        else:
            post.time_remaining = "In Progress"

    return render(request, "upcoming_posts.html", {
        "upcoming_posts": upcoming_posts,
        "remove": remove
    })
예제 #3
0
def run():
    global twitch_client_id
    User.objects.all().delete()

    with open("config/config.json") as file:
        data = json.load(file)
        twitch_client_id = data['twitch-client-id']
        util.timezone = pytz.timezone(data['timezone'])

        user = data['login']
        User.objects.create_user(username=user['username'],
                                 email='',
                                 password=user['password'])
    util.validate()
    imageio.plugins.ffmpeg.download(directory=settings.BASE_DIR)

    # Redirect STD out
    if not settings.DEBUG:
        debug = open('debug.log', 'a')
        sys.stdout = debug
        sys.stderr = debug

    # Reset tmp directory
    if os.path.exists("tmp"):
        shutil.rmtree("tmp")
    os.makedirs("tmp")

    # Remove any outdated posts that weren't posted for some reason
    current_day = util.get_current_time().day
    for queued_post in Post.objects.filter(posted=False):
        if queued_post.queued_time.day != current_day:
            queued_post.delete()

    th = threading.Thread(target=timer)
    th.daemon = True
    th.start()
예제 #4
0
 def is_active(self):
     return self.created_after <= util.get_current_time().date()
예제 #5
0
def add_post_data(message, post):
    return message.format(
        clip=post.clip_url,
        account=post.account.username,
        type=account_types.get(post.account.type),
        time=util.get_current_time().strftime("%Y-%m-%d %H:%M"))
예제 #6
0
def process_queue(minute):
    for post in Post.objects.filter(posted=False):
        # post_minute = (80 * post.post_time.hour) + post.post_time.minute
        if minute >= post.post_minute:
            try:
                print("Downloading...")
                local_video_path = "tmp/" + post.download_url.split("/")[-1]
                local_thumbnail_path = "tmp/" + post.thumbnail_url.split(
                    "/")[-1]
                resized_video_path = local_video_path + "-resized.mp4"
                urllib.request.urlretrieve(post.download_url, local_video_path)
                urllib.request.urlretrieve(post.thumbnail_url,
                                           local_thumbnail_path)
                print("Done!")
                if post.account.type == TWITTER:
                    twitterupload.VideoTweet(
                        file_name=local_video_path,
                        caption=post.caption,
                        consumer_key=post.account.consumer_key,
                        consumer_secret=post.account.consumer_key_secret,
                        token=post.account.access_token,
                        token_secret=post.account.access_token_secret).tweet()
                else:
                    # clip = moviepy.editor.VideoFileClip(local_video_path)
                    # # resize(clip, width=600)
                    # clip_resized = resize(clip, width=600)
                    # clip_resized.write_videofile(local_video_path, bitrate="50k")
                    # clip.close()
                    if imageio.plugins.ffmpeg.get_platform().startswith("win"):
                        os.system(
                            "cd ffmpeg && {ffmpeg} -i ../{source_video} "
                            "-vf scale=1560:1080,setdar=13:9 ../{resized_video}"
                            .format(ffmpeg=ffmpeg,
                                    source_video=local_video_path,
                                    resized_video=resized_video_path))
                    else:
                        os.system(
                            "./ffmpeg/{ffmpeg} -i {source_video} -vf scale=1560:1080,setdar=13:9 {resized_video}"
                            .format(ffmpeg=ffmpeg,
                                    source_video=local_video_path,
                                    resized_video=resized_video_path))

                    image = Image.open(local_thumbnail_path)
                    # width, height = image.size
                    # size = max(256, width, height)
                    # print(width, height)
                    # resized = Image.new('RGB', (size, size))
                    # resized.paste(image, ((size - width) // 2, (size - height) // 2))
                    # resized.save(local_thumbnail_path)
                    resized = image.resize((600, 400), Image.ANTIALIAS)
                    resized.save(local_thumbnail_path)
                    image.close()

                    api = InstagramAPI(username=post.account.username,
                                       password=post.account.password)
                    if api.login():
                        time.sleep(3)
                        print("Uploading...")
                        api.uploadVideo(resized_video_path,
                                        local_thumbnail_path,
                                        caption=post.caption)
                        time.sleep(2)
                        api.logout()
                        print("Finished Uploading")
                        time.sleep(2)
                    else:
                        raise AuthenticationError(
                            "Failed to login to Instagram account: " +
                            post.account.username)
                # Immediately update post data if there was no error
                post.post_time = util.get_current_time()
                post.posted = True
                post.save()

                # Delete temporary files
                os.remove(local_video_path)
                os.remove(local_thumbnail_path)
                if resized_video_path != local_video_path:
                    os.remove(resized_video_path)

                # Log result
                log_message(
                    add_post_data(
                        "{time}) posted clip on {account} ({type}). Video URL: {clip}",
                        post))
            except Exception as e:
                traceback.print_exc()
                log_message(
                    add_post_data(
                        "{time}) FAILED TO POST ON {account} ({type}). VIDEO URL: {clip}",
                        post) + ", ERROR: " + str(e))
                # with open("application.log", "a+") as log_file:
                #     traceback.print_exc(file=log_file)
                post.delete()