def get_image_from_url(self, destDirectory):

        self.destDirectory = destDirectory
        ext = self.imageUrl.split(".")[-1]
        self.ext = ext
        if ext not in RedditImage.validImageTypes:
            return

        if self.imagePath != "":
            return

        response = requests.get(self.imageUrl)
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError:
            log("There was an exception thrown while getting url HTTP Status:",
                response.status_code)
            return

        content = response.content

        descriptor, self.imagePath = mkstemp(suffix="." + ext,
                                             dir=destDirectory)

        #print("File Saved at " + self.imagePath)
        with os.fdopen(descriptor, "wb") as imageFile:
            imageFile.write(content)
Esempio n. 2
0
def remove_all_files(directory):
    log("Removing all files in directory:", directory, is_heading=True)
    prev = os.listdir(directory)
    for f in prev:
        full = os.path.join(directory, f)
        os.remove(full)
        log("File Removed:", full)
Esempio n. 3
0
    def combine_images(self, final_image_path):
        width_diff = 0
        if self.get_current_aspect_ratio() > get_screen_aspect_ratio():
            # need to add more height to the image
            image_width = self.get_total_size(RedditImage.WIDTH)
            image_height = int(image_width // get_screen_aspect_ratio())
        else:
            # need to add more width to the image

            image_height = self.get_max_size(RedditImage.HEIGHT)
            combined_width = self.get_total_size(RedditImage.WIDTH)
            image_width = int(image_height * get_screen_aspect_ratio())
            width_diff = (image_width - combined_width) // (len(self.selectedImages) - 1)

        temp = Image.new("RGB", (image_width, image_height))

        log("Start Image Combining Process")
        beg_x = 0
        nextColor = None
        for pic in self.selectedImages:
            portrait = Image.open(pic.imagePath).convert('RGB')
            if nextColor is not None:
                # make gradient for in between images
                currColor = average_pixel_color(portrait, LEFT)
                do_gradient(temp, (beg_x - width_diff, 0), (beg_x, image_height - 1), nextColor, currColor)
            nextColor = average_pixel_color(portrait, RIGHT)
            height_factor = (image_height - RedditImage.get_size_data(pic, RedditImage.HEIGHT)) // 2
            temp.paste(portrait, (beg_x, height_factor))
            beg_x += RedditImage.get_size_data(pic, RedditImage.WIDTH) + width_diff

        log("Save Resulting Image")
        temp.save(final_image_path, format="JPEG")
        log("Combined Image Saved")
Esempio n. 4
0
    init_directories()
    signal.signal(signal.SIGTERM, sigterm_handler)

    args = parser.parse_args()

    reddit_logging.VerboseLogging = args.verbose

    if args.log_file is None or not os.path.exists(args.log_file):
        reddit_logging.LoggingFile = os.path.join(base_directory,
                                                  "PictureSource", "log.txt")
    else:
        reddit_logging.LoggingFile = args.log_file

    reddit_logging.FileLogging = not args.no_log_file

    if args.interactive:
        RedditShell().cmdloop()
    else:

        reddit_logging.log("Begin Program")
        try:

            apiObject = RedditAPI(args)
            apiObject.do_daily_iteration()
            if not args.no_weekly:
                apiObject.do_weekly_iteration()
        except Exception:
            reddit_logging.log(traceback.format_exc())

        reddit_logging.log("End Program")
Esempio n. 5
0
    def do_daily_iteration(self):
        log("Start Daily Iteration", is_heading=True)
        self.incorrect_aspect = []
        self.correct_aspect = []
        dailyDirectory = os.path.join(dest_directory, "DailySource")
        remove_all_files(dailyDirectory)
        progressBar = None
        try:
            urls = self.get_submissions_for_subreddit("day")
            log("URLS Gathered")

            totalCount = len(urls)
            if self.args.show_progress:
                progressBar = Bar("Downloading Daily Images",
                                  max=totalCount,
                                  suffix='%(index)d / %(max)d  %(percent)d%%')
                progressBar.start()
            # get suitable image for desktop background
            while len(urls) != 0:
                # select specific url at random
                attempt, urls = get_random_url(urls)
                image_url, post_permalink = attempt
                log("Process URL:", image_url, "URLS Left:", len(urls))

                # save first attempt at okay file url
                imageObj = RedditImage(image_url, post_permalink)
                imageObj.get_image_from_url(dailyDirectory)
                if not imageObj.image_downloaded():
                    continue

                if imageObj.image_is_landscape():
                    self.correct_aspect.append(imageObj)
                else:
                    self.incorrect_aspect.append(imageObj)
                if progressBar is not None:
                    progressBar.next()
                log("URL has been processed")

            if progressBar is not None:
                progressBar.finish()
                progressBar = None

            RedditDatabase().insert_images(self.correct_aspect +
                                           self.incorrect_aspect)
            if len(self.incorrect_aspect) > 0:
                log("Start Image Combining Process")
                ci = CombineImages(self.incorrect_aspect, dest_directory)
                log("Save Resulting Image")
                pathOfResult = ci.do_combine_landscape_process()
                RedditDatabase().insert_combined(ci)
                log("Set Image as Desktop Background")
                RedditImage.set_image_to_desktop_background(pathOfResult)
            else:
                self.correct_aspect[0].set_to_desktop_background()
        finally:
            # cleanup all images that had been temporarily downloaded
            if progressBar is not None:
                progressBar.finish()
Esempio n. 6
0
    def do_weekly_iteration(self):
        if RedditAPI.should_run_weekly():
            log("Start Weekly Iteration", is_heading=True)
            initialSource = os.path.join(base_directory, "PictureSource",
                                         "LockScreenSource")
            finalSource = os.path.join(base_directory, "PictureSource",
                                       "LockScreen")
            remove_all_files(initialSource)
            remove_all_files(finalSource)
            progressBar = None
            try:
                weekly_urls = self.get_submissions_for_subreddit("week")
                log("URLS Gathered")
                totalCount = len(weekly_urls)
                landscape = []
                portrait = []
                if self.args.show_progress:
                    progressBar = Bar(
                        "Downloading Weekly Images",
                        max=totalCount,
                        suffix='%(index)d / %(max)d  %(percent)d%%')
                    progressBar.start()

                with open(
                        os.path.join(base_directory, "PictureSource",
                                     "lockScreenStat.txt"), "w") as f:
                    while len(weekly_urls) > 0:
                        # select specific url at random
                        attempt, urls = get_random_url(weekly_urls)
                        image_url, post_permalink = attempt

                        log("Process URL:", image_url, "URLS Left:", len(urls))

                        # get image and save if able
                        imageObj = RedditImage(image_url, post_permalink)
                        imageObj.get_image_from_url(initialSource)
                        if imageObj.image_is_landscape():
                            landscape.append(imageObj)
                        else:
                            portrait.append(imageObj)
                        if imageObj.image_downloaded():
                            f.write(str(imageObj) + "\n")

                        if progressBar is not None:
                            progressBar.next()

                        log("URL has been processed")

                    if progressBar is not None:
                        progressBar.finish()

                    for imageObj in landscape:
                        imageObj.move_to_folder(finalSource)
                        print("did the copy")

                    RedditDatabase().insert_images(landscape + portrait)

                    # iterate through creating landscape photos
                    resulting = CombineImages.iterate_combine_landscape(
                        portrait, finalSource)
                    RedditDatabase().insert_all_combined(resulting)
                self.set_weekly_run_file()
            finally:
                if progressBar is not None:
                    progressBar.finish()