php script does not read “completed” status out of api request correctly

thanks for checking out my question. I created a PHP script that sends API requests via the DASH API. After the script sends its request, it should start a job on DASH. However, the script is having trouble retrieving the “completed” status properly and ends up running in a loop, continuously requesting the job status until the cron job is forced to end. The possible job statuses are “in progress,” “completed,” and “failed.”

Here are the relevant parts of my script:

function create_batch_job($access_token, $asset_id, $batch_item_id)
{
    $batch_job_url = 'https://api-v2.dash.app/embeddable-link-batch-jobs';
    $headers = [
        "Authorization: Bearer $access_token",
        'Content-Type: application/json'
    ];

    $body = json_encode([
        "items" => [
            [
                "batchItemId" => "my-item-$batch_item_id",
                "assetId" => $asset_id,
                "assetFileId" => null,
                "presetParameters" => []
            ]
        ],
        "transformationDescription" => [
            "type" => "CUSTOM",
            "candidateTransformations" => [
                [
                    "criteria" => [
                        [
                            "type" => "MATCHES_MEDIA_TYPES",
                            "mediaTypes" => [
                                ["type" => "image", "subType" => "png"]
                            ]
                        ]
                    ],
                    "transformation" => []
                ]
            ]
        ]
    ]);

    list($status, $response) = http_request('POST', $batch_job_url, $headers, $body);

    log_message("Request URL: $batch_job_url", $GLOBALS['responseLogFile']);
    log_message("Request headers: " . json_encode($headers), $GLOBALS['responseLogFile']);
    log_message("Request body: $body", $GLOBALS['responseLogFile']);
    log_message("Response status: $status", $GLOBALS['responseLogFile']);
    log_message("Response body: $response", $GLOBALS['responseLogFile']);

    if ($status == 200) {
        log_api_response($response);
        $response_data = json_decode($response, true);
        return $response_data['id'];
    } else {
        log_api_response($response);
        throw new Exception('Batch job creation failed');
    }
}

function check_job_status($access_token, $job_id, $batch_item_id)
{
    $job_status_url = "https://api-v2.dash.app/embeddable-link-batch-jobs/$job_id";
    $headers = [
        "Authorization: Bearer $access_token",
        'Content-Type: application/json'
    ];

    for ($attempt = 0; $attempt < 3; $attempt++) { 
        sleep(5); 
        log_message("Checking job status for URL: $job_status_url (Attempt " . ($attempt + 1) . "/3)", $GLOBALS['responseLogFile']);

        list($status_code, $response) = http_request('GET', $job_status_url, $headers);
        log_message("Check job status response: $status_code $response", $GLOBALS['responseLogFile']);

        if ($status_code == 200) {
            $response_data = json_decode($response, true);
            $status = $response_data['status'];

            if ($status === 'COMPLETED') {
                log_message("Job $job_id completed successfully.", $GLOBALS['responseLogFile']);

                
                $result_key = "my-item-$batch_item_id";
                if (isset($response_data['result']['results'][$result_key]['result']['url'])) {
                    $url = $response_data['result']['results'][$result_key]['result']['url'];
                    log_message("Job completed, URL: $url", $GLOBALS['responseLogFile']);

                    
                    file_put_contents('completed_jobs_urls.txt', "Job $job_id URL: $urln", FILE_APPEND);

                    
                    return [$status, $response_data];
                } else {
                    log_message("Error: No URL found in the job response.", $GLOBALS['responseLogFile']);
                }
            } elseif ($status === 'FAILED') {
                log_message("Job $job_id failed.", $GLOBALS['responseLogFile']);
                return [$status, $response_data]; 
            } else {
                log_message("Job $job_id in progress... Status: $status", $GLOBALS['responseLogFile']);
            }
        } else {
            throw new Exception('Job status check failed');
        }
    }

    throw new Exception("Job $job_id did not complete after 3 attempts");
}



function process_assets()
{
    global $csvFile, $completedJobsFile, $jobIdsFile;

    log_api_response("Cron job started successfully.");

    $access_token = authenticate();

    $csv = array_map('str_getcsv', file($csvFile));
    $header = array_shift($csv); 
    $outfile = fopen($completedJobsFile, 'w'); 
    fputcsv($outfile, ['jobId', 'status', 'url']); 

    $batch_item_id = 1; 

    foreach ($csv as $idx => $row) {
        $asset_id = $row[0]; 
        log_message("Processing asset " . ($idx + 1) . ": $asset_id", $GLOBALS['responseLogFile']);

        try {
            
            $job_id = create_batch_job($access_token, $asset_id, $batch_item_id);

            if ($job_id) {
                file_put_contents($jobIdsFile, "$job_idn", FILE_APPEND);

                
                list($status, $response_data) = check_job_status($access_token, $job_id, $batch_item_id);

                if ($status === 'COMPLETED') {
                    
                    $result_key = "my-item-$batch_item_id";
                    if (isset($response_data['result']['results'][$result_key]['result']['url'])) {
                        $url = $response_data['result']['results'][$result_key]['result']['url'];
                        fputcsv($outfile, ['jobId' => $job_id, 'status' => $status, 'url' => $url]);
                        log_message("Job $job_id completed and saved to file.", $GLOBALS['responseLogFile']);
                    }
                }

                $batch_item_id++; 
            }
        } catch (Exception $e) {
            log_message("Error processing asset ID $asset_id: " . $e->getMessage(), $GLOBALS['responseLogFile']);
        }
    }

    fclose($outfile); 
}


process_assets();

I wanted the script run one asset id at a time, extract the link i need and write the link + id into a csv file. But the script is unable to find the “completed” status in the api request, so all the following procedure is not happening either. Why is the script unable to find the “completed” statement from the api job?

New contributor

Coffee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

6

The problem lies in the check_job_status function which was checking the “status” field, when it should check the “type” field.

I changed the function to check for the type field and now its all working how it was supposed to be.

 if ($type === 'COMPLETED') instead of `if ($status === 'COMPLETED')`

New contributor

Coffee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật