bosta

mail@pastecode.io avatar
unknown
python
2 years ago
6.0 kB
2
Indexable
Never
import calendar
import pprint
from ntpath import realpath
import shutil
from dateutil import parser
from datetime import datetime
import re
import os
import glob
import time
from math import comb
import requests
import json
from functools import reduce


# 🌎 OBTENIENDO data de Twitch API
url = "https://api.twitch.tv/helix/videos?first=100&user_id=489264649"

payload = {}
headers = {
    'client-id': '0tyd78ctf548v7d88osdan5992q2kc',
    'Authorization': 'Bearer uyhtsfa4rbm77vrhyzqrmg5tbbu63i'
}

response = requests.request(
    "GET", url, headers=headers, data=json.dumps(payload))
result = response.json()
data = result["data"]
# pprint.pprint(data)
# published_at = data["published_at"]
# duration = data["duration"]
# title = data["title"]


def durationSeconds(timeExprs):
    # ⌚ FOO - convierte timesampt tipo 3h30m50s a SEGs
    units = {'h': 3600, 'm': 60, 's': 1}
    regex = r"(\d+)([hms])"
    r = re.compile(r"(\d+)([hms])")
    seconds = 0
    m = r.findall(timeExprs)
    for i in m:
        seconds += int(i[0]) * units[i[1]]
        return float(seconds)

# stream_duration_seconds = durationSeconds(duration)


def parse_date(date_to_parse):
    # πŸ“… PARSEANDO fecha tipo 2022-04-10T02:48:53Z a SEG (published_at)
    dt = parser.parse(date_to_parse)
    parsed_date = calendar.timegm(dt.utctimetuple())
    return parsed_date

# latest_stream_dat = parse_date(published_at)


# πŸ”΄ TUPLAS streams
# tupla (nombre stream, epoch comienzo, epoch fin --epoch comienzo + duracion en seg--)
total_streams = 0
touple_streams = []
for item in data:
    total_streams += 1
    touple_streams.append((item["title"], parse_date(
        item["published_at"]), parse_date(
        item["published_at"])+durationSeconds(item["duration"])))
# touple is ORDERED by STREAM DATE START, 1st one is LAST STREAM YOU MADE
touple_streams = tuple(touple_streams)
# print(touple_streams)
# print("TOTAL de STREAMS πŸ‘‰πŸ½", total_streams)

# πŸ“ LIST ARCHIVOS: armando tupla de archivos MAS JOVENES q 3 meses
## tupla (nombre_archivo, fecha_seg_creacion, path_archivo)
three_months_in_sec = 7890000
path = r"C:\Users\yerba\Documents\diseΓ±o - video\__MATERIAL\_stream - vods y marker logfiles (infowriter)\*"
list_of_files = glob.glob(path)
# print("--------------------------------------------------------")
# print("LIST ARCHIVOS πŸ‘‰πŸ½πŸ‘‰πŸ½πŸ‘‰πŸ½", list_of_files)
# print("fecha hace 3 meses en epoch", time.time() - three_months_in_sec)
older_than_3_months = []
younger_than_3_months = []
for filename in list_of_files:
    if re.search('orphan csv dump', filename):
        # print(filename,"SKIPPED πŸ‡πŸ‡πŸ‡")
        continue
    if (os.path.getctime(filename) < time.time() - three_months_in_sec):
        # print("πŸ‘΄πŸ½ archivo es MAS VIEJO q 3 meses πŸ‘‰πŸ½", os.path.basename(filename))
        older_than_3_months.append(
            (os.path.basename(filename), os.path.getctime(filename), path[:-1]))
    elif os.path.getctime(filename) > time.time() - three_months_in_sec:
        # print("πŸ‘ΆπŸ½ archivo es MAS NUEVO q 3 meses πŸ‘‰πŸ½", os.path.basename(filename))
        younger_than_3_months.append(
            (os.path.basename(filename), os.path.getctime(filename), path[:-1]))
    else:
        print("WTF, el archivo", os.path.basename(
            filename), "no cumple ninguna condicion")


def colored(r, g, b, text):
    return f"\033[38;2;{r};{g};{b}m{text}\033[38;2;255;255;255m"


# ❗ REVISANDO y RENOMBRANDO archivos
found = False
for item in younger_than_3_months:
    for stream in touple_streams:
        # print("condicion 1 πŸ‘‰πŸ½", stream[1] <= item[1])
        # print("condicion 2 πŸ‘‰πŸ½", stream[2] >= item[1])
        condition1 = (float(stream[1]) <= float(item[1]) or float(
            stream[1])-300 <= float(item[1]))
        condition2 = float(stream[2]) >= float(item[1])
        if condition1 and condition2:
            # print(
            #     colored(0, 255, 0, "❗❗❗ STREAM COINCIDENTE ENCONTRADO:"))
            # print(stream[0])
            found = True
            if not stream[0] in item[0]:
                # print("βœ… WOULD rename", item[0], "to",
                #       item[2]+stream[0]+" - "+item[0])
                original_name = item[2]+item[0]
                modified_name = item[2]+stream[0]+" - "+item[0]
                print("PREVIOUS NAME:", original_name)
                print("CURRENT NAME:", modified_name)
                os.rename(original_name, modified_name)
            else:
                # print("❌ would NOT rename",
                #       item[0], "because it already has the stream name of the stream...", stream[0])
                pass
            break
        found = False
    if found:
        pass
    else:
        print("❌ STREAM NO ENCONTRADO PARA:")
        orphan_csv_path = r"C:\Users\yerba\Documents\diseΓ±o - video\__MATERIAL\_stream - vods y marker logfiles (infowriter)\orphan csv dump\\"
        original_name = item[2]+item[0]
        modified_name = orphan_csv_path+"orphan csv - "+item[0]
        print("PREVIOUS NAME:", original_name)
        print("CURRENT NAME:", modified_name)
        if orphan_csv_path not in item[0]:
            os.rename(original_name, modified_name)

# RENOMBRANDO archivos mas viejos q 3 meses
# print("πŸ‘΄πŸ½ πŸ‘‰πŸ½πŸ”₯ REMOVIENDO csv VIEJOS a una carpeta")
for item in older_than_3_months:
    orphan_csv_path = r"C:\Users\yerba\Documents\diseΓ±o - video\__MATERIAL\_stream - vods y marker logfiles (infowriter)\orphan csv dump\\"
    original_name = item[2]+item[0]
    modified_name = orphan_csv_path+"older than 3 months and orphan csv - "+item[0]
    # print("πŸ‘΄πŸ½ PREVIOUS NAME:", original_name)
    # print("πŸ‘΄πŸ½ CURRENT NAME:", modified_name)
    if orphan_csv_path not in item[0]:
        os.rename(original_name, modified_name)