From c8d107f98a3b53a4bc9ca32a484968d915d61e92 Mon Sep 17 00:00:00 2001 From: Dmitriy Kalinin <2e3s19@gmail.com> Date: Thu, 3 Nov 2016 03:50:27 +0600 Subject: [PATCH] Text format for the backup No need to keep the JSON just to be able to search. Also fixed the messages order issue: API search returns incorrectly sorted results --- src/ExportUserHistory.php | 60 ++++++++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/src/ExportUserHistory.php b/src/ExportUserHistory.php index b250e48..b24ce85 100644 --- a/src/ExportUserHistory.php +++ b/src/ExportUserHistory.php @@ -83,6 +83,30 @@ public function execute(InputInterface $input, OutputInterface $output) } } + /** + * @param $file Resource backup file + * @param array $result History search result items + */ + private function writeData($file, array $result) + { + usort($result, function ($row1, $row2) { + return ($row1['date'] < $row2['date']) ? -1 : 1; + }); + foreach ($result as $row) { + if ($row['type'] !== 'message') { + continue; + } + $time = date('Y-m-d H:i:s', strtotime($row['date'])); + $fromName = $row['from']['name']; + $fromMention = $row['from']['mention_name']; + fwrite( + $file, + "{$time} -- {$fromName} (@{$fromMention})" . PHP_EOL + . $row['message'] . PHP_EOL + ); + } + } + /** * * @param string $token @@ -96,10 +120,18 @@ private function exportHistory(string $token, string $user) $limit = 1000; $offset = 0; + // Keep windows compatibility + $filename = str_replace(':', '-', "{$now}.{$user}.txt"); + + $file = fopen("{$this->dir}/{$filename}", 'w'); + if ($file === false) { + throw new RuntimeException("Impossible to write into {$filename}"); + } else { + echo "File [{$filename}] created", PHP_EOL; + } + try { $data = []; - $page = []; - do { echo "Fetching the {$limit} records from {$offset}...", PHP_EOL; @@ -116,30 +148,24 @@ private function exportHistory(string $token, string $user) 'max-results' => $limit, 'start-index' => $offset, 'date' => $now, + 'end-date' => null, ], ] ); - $result = json_decode((string) $response->getBody(), true); - + $result = json_decode((string) $response->getBody(), true); + if (!empty($result['items'])) { - $page = $result['items']; - $data = array_merge($data, $page); - + $data = array_merge($data, $result['items']); + $offset += $limit; } - } while ($page); - - // Keep windows compatibility - $file = str_replace(':', '-', "{$now}.{$user}.json"); - - if (file_put_contents("{$this->dir}/{$file}", json_encode($data, JSON_PRETTY_PRINT)) === false) { - throw new RuntimeException('Impossible to write the file'); - } - - echo "File [{$file}] created", PHP_EOL; + } while (!empty($result['items'])); + $this->writeData($file, $data); } catch (ClientException $e) { echo $e->getMessage(), PHP_EOL; } + + fclose($file); } }