#!/usr/bin/env python3

# download_muzei_archive.py
# 2022-02-02
# by Gernot Walzl

# Muzei is an app for Android that refreshes the home screen every day
# with famous art. This script downloads the Muzei archive of a month.
# Homepage: https://muzei.co/
# API Today: https://muzeiapi.appspot.com/featured
# API Archive: https://storage.googleapis.com/muzeifeaturedart/%Y%m.txt

import argparse
import datetime
import json
import os
import requests


class MuzeiArchiveDownloader:
    url_muzei = "https://storage.googleapis.com/muzeifeaturedart/"

    def request_archive_meta(self, date_yearmonth):
        str_yearmonth = date_yearmonth.strftime("%Y%m")
        url = self.url_muzei+"archivemeta/"+str_yearmonth+".txt"
        response = requests.get(url)
        r_text = response.text
        r_json = r_text[0:r_text.find(']')+1]
        return r_json

    @staticmethod
    def extract_filenames(str_json_archive):
        result = []
        for obj in json.loads(str_json_archive):
            url_thumb = obj['thumb_url']
            filename = url_thumb[url_thumb.rfind('/')+1:len(url_thumb)]
            result.append(filename)
        return result

    def download_file(self, filename, dir_out):
        url = self.url_muzei+"lt-full/"+filename
        response = requests.get(url)
        with open(dir_out+"/"+filename, 'wb') as f_out:
            f_out.write(response.content)

    def download_month(self, year, month):
        date_yearmonth = datetime.date(year, month, 1)
        dir_out = date_yearmonth.strftime("%Y/%m")
        if not os.path.exists(dir_out):
            os.makedirs(dir_out)

        str_json_arch = self.request_archive_meta(date_yearmonth)
        path_arch = dir_out
        path_arch += "/archivemeta_"+date_yearmonth.strftime("%Y-%m")+".json"
        with open(path_arch, 'w') as f_arch:
            f_arch.write(str_json_arch)

        for filename in self.extract_filenames(str_json_arch):
            print(filename)
            self.download_file(filename, dir_out)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('year', type=int)
    parser.add_argument('month', type=int)
    args = parser.parse_args()

    downloader = MuzeiArchiveDownloader()
    downloader.download_month(args.year, args.month)


if __name__ == '__main__':
    main()