Replace some missing screenshots and detail images with image from blackcharcz's...
[ouya-game-data.git] / bin / replace-game-images-by-list
1 #!/usr/bin/env php
2 <?php
3 /**
4  * Replace all game image URLs listed in the given CSV file with
5  * the ones in the second CSV column
6  */
7 if (!isset($argv[1])) {
8     fwrite(STDERR, "CSV file missing\n");
9     exit(1);
10 }
11 $imageUrlMapFile = $argv[1];
12
13 $hdl = fopen($imageUrlMapFile, 'r');
14 if (!$hdl) {
15     fwrite(STDERR, "Cannot load image url map file\n");
16 }
17 $mapping = [];
18 while ($data = fgetcsv($hdl, 4096, ',')) {
19     if (count($data) == 2) {
20         $mapping[$data[0]] = $data[1];
21     }
22 }
23 if (count($mapping) == 0) {
24     fwrite(STDERR, "Image url map file is empty\n");
25 }
26
27
28 $files = glob(__DIR__ . '/../games/*.json');
29 foreach ($files as $file) {
30     $data = json_decode(file_get_contents($file));
31     $package = $data->packageName;
32     replaceImage($data->media->discover);
33     if (count($data->media->screenshots ?? [])) {
34         $pos = 0;
35         foreach ($data->media->screenshots as &$url) {
36             replaceImage($url);
37         }
38     }
39     if (count($data->media->details ?? [])) {
40         $pos = 0;
41         foreach ($data->media->details as $detail) {
42             if ($detail->type == 'image') {
43                 replaceImage($detail->url);
44                 replaceimage($detail->thumb);
45             }
46         }
47     }
48     file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT) . "\n");
49 }
50
51 function replaceImage(&$url)
52 {
53     global $mapping;
54
55     preg_match('#https://www.filepicker.io/api/file/([^/]+)/convert\?w=720#', $url, $matches);
56     if (isset($matches[1])) {
57         $url = 'https://d3e4aumcqn8cw3.cloudfront.net/api/file/' . $matches[1];
58     }
59
60     if (strlen($url) == 55) {
61         preg_match('#https://www.filepicker.io/api/file/([^/]+)$#', $url, $matches);
62         if (isset($matches[1])) {
63             $url = 'https://d3e4aumcqn8cw3.cloudfront.net/api/file/' . $matches[1];
64         }
65     }
66
67     if (isset($mapping[$url])) {
68         $url = $mapping[$url];
69     }
70 }
71 ?>