/** * Execute the console command. * * @param Repository $config * @param Container $container * * @return mixed * @throws \InvalidArgumentException * @throws \RuntimeException * @throws \LogicException * @throws \Exception */ public function handle(Repository $config, Container $container) { $this->syncUsers($config, $container); $config->set('gitter.output', false); $client = Client::make($config->get('gitter.token'), $this->argument('room')); $room = $container->make(Room::class); $this->karma = new Validator(); $request = $this->cursor($client, $room); $count = 1; // Start number $page = 0; // Current page $chunk = 100; // Per page while (true) { $messageChunk = $request($chunk, $chunk * $page++); if (!count($messageChunk)) { $this->output->write(sprintf("\r Well done. <comment>%s</comment> Messages was be loaded.", $count)); break; } foreach ($messageChunk as $m) { echo "\rLoad message: {$count} "; $count++; } $name = 'sync/' . $page . '.json'; echo '...dump to ' . $name; file_put_contents(storage_path($name), json_encode($messageChunk)); } echo "\n"; $this->output->write('Flush database karma increments'); Karma::query()->where('room_id', $room->id)->delete(); $this->output->write('Start message parsing.'); $finder = (new Finder())->files()->in(storage_path('sync'))->name('*.json')->sort(function ($a, $b) { $parse = function (\SplFileInfo $file) { return str_replace('.json', '', $file->getFilename()); }; return $parse($b) <=> $parse($a); }); $count = 1; foreach ($finder as $file) { $messages = json_decode($file->getContents(), true); foreach ($messages as $message) { $message = Message::fromGitterObject($message); echo "\r" . $count++ . ' messages parsing: ' . $message->created_at; usleep(100); $this->onMessage($message); } unlink($file->getRealPath()); } }
/** * @throws InvalidArgumentException * @return Client */ public function listen() { $client = $this->client->stream('messages', ['roomId' => $this->id])->on(Stream::EVENT_MESSAGE, function ($stream, $data) { $this->onMessage(Message::fromGitterObject($data)); })->on(Stream::EVENT_END, [$this, 'onClose'])->on(Stream::EVENT_ERROR, [$this, 'onError']); return $client; }