HEX
Server: Apache/2.4.63 (Unix)
System: Linux Synopilou92 4.4.302+ #72806 SMP Mon Jul 21 23:16:00 CST 2025 x86_64
User: pilou92 (1026)
PHP: 8.0.30
Disabled: NONE
Upload Files
File: /volume1/@appstore/SynologyPhotos/migration/python/check_video_convert_task.py
#!/usr/bin/env python3

import json, os, sys

import pg8000

candidate_list_file = "/var/packages/SynologyPhotos/var/stuck_video_convert_task"


def init_cursor():
    user = "postgres"
    unix_sock = "/var/run/postgresql/.s.PGSQL.5432"
    database = "synofoto"
    conn = pg8000.connect(user, unix_sock=unix_sock, database=database)

    cursor = conn.cursor()
    cursor.execute("SET CLIENT_ENCODING TO 'UTF8'")

    return cursor


def remove_candidate_list_file():
    if os.path.exists(candidate_list_file):
        os.remove(candidate_list_file)


def read_candidate_list_file():
    if not os.path.exists(candidate_list_file):
        return []

    input_file = open(candidate_list_file)
    candidate_list_json = []
    try:
        candidate_list_json = json.load(input_file)
    except:
        pass
    input_file.close()

    return candidate_list_json


def stop_timer_service():
    os.system("systemctl stop pkg-SynologyPhotos-check-video-convert-task.timer")


def get_running_thumbnail_task_ids(cursor):
    cursor.execute(
        """
        SELECT id
        FROM index_queue
        WHERE type = 2 AND status = 1
        LIMIT 1000
        """
    )

    tasks = cursor.fetchall()

    result = []
    for [id] in tasks:
        result.append(id)

    return result


def delete_task_by_ids(cursor, ids):
    cursor.execute(
        """
        DELETE
        FROM index_queue
        WHERE id IN ({})
        """.format(
            ",".join(str(id) for id in ids)
        )
    )

    cursor.execute("COMMIT")


def main():

    if (
        os.path.exists("/var/spool/thumb_create.queue")
        or os.path.exists("/var/spool/flv_create.queue")
        or os.path.exists("/var/spool/thumb_create.queue.tmp")
        or os.path.exists("/var/spool/flv_create.queue.tmp")
    ):
        remove_candidate_list_file()
        sys.exit(0)

    cursor = init_cursor()

    task_ids_to_be_removed = read_candidate_list_file()
    remove_candidate_list_file()

    if len(task_ids_to_be_removed) > 0:
        delete_task_by_ids(cursor, task_ids_to_be_removed)

    task_ids = get_running_thumbnail_task_ids(cursor)

    if len(task_ids) == 0:
        stop_timer_service()
        sys.exit(0)

    output_file = open(candidate_list_file, "w")
    json.dump(task_ids, output_file)
    output_file.close()


if __name__ == "__main__":
    main()