74df284e12ae9ae3e0e06c73934175de3540f639
[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     replaceImage($data->media->large);
34     if (count($data->media->screenshots ?? [])) {
35         $pos = 0;
36         foreach ($data->media->screenshots as &$url) {
37             replaceImage($url);
38         }
39     }
40     if (count($data->media->details ?? [])) {
41         $pos = 0;
42         foreach ($data->media->details as $detail) {
43             if ($detail->type == 'image') {
44                 replaceImage($detail->url);
45                 replaceimage($detail->thumb);
46             }
47         }
48     }
49     file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT) . "\n");
50 }
51
52 function replaceImage(&$url)
53 {
54     global $mapping;
55
56     preg_match('#https://www.filepicker.io/api/file/([^/]+)/convert\?w=720#', $url, $matches);
57     if (isset($matches[1])) {
58         $url = 'https://d3e4aumcqn8cw3.cloudfront.net/api/file/' . $matches[1];
59     }
60
61     if (strlen($url) == 55) {
62         preg_match('#https://www.filepicker.io/api/file/([^/]+)$#', $url, $matches);
63         if (isset($matches[1])) {
64             $url = 'https://d3e4aumcqn8cw3.cloudfront.net/api/file/' . $matches[1];
65         }
66     }
67
68     if (isset($mapping[$url])) {
69         $url = $mapping[$url];
70     }
71 }
72 ?>