Passed
Push — master ( 785cca...ff6f10 )
by Morris
10:35
created
apps/files_external/lib/Command/Notify.php 2 patches
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -45,252 +45,252 @@
 block discarded – undo
45 45
 use Symfony\Component\Console\Output\OutputInterface;
46 46
 
47 47
 class Notify extends Base {
48
-	/** @var GlobalStoragesService */
49
-	private $globalService;
50
-	/** @var IDBConnection */
51
-	private $connection;
52
-	/** @var ILogger */
53
-	private $logger;
48
+    /** @var GlobalStoragesService */
49
+    private $globalService;
50
+    /** @var IDBConnection */
51
+    private $connection;
52
+    /** @var ILogger */
53
+    private $logger;
54 54
 
55
-	function __construct(GlobalStoragesService $globalService, IDBConnection $connection, ILogger $logger) {
56
-		parent::__construct();
57
-		$this->globalService = $globalService;
58
-		$this->connection = $connection;
59
-		$this->logger = $logger;
60
-	}
55
+    function __construct(GlobalStoragesService $globalService, IDBConnection $connection, ILogger $logger) {
56
+        parent::__construct();
57
+        $this->globalService = $globalService;
58
+        $this->connection = $connection;
59
+        $this->logger = $logger;
60
+    }
61 61
 
62
-	protected function configure() {
63
-		$this
64
-			->setName('files_external:notify')
65
-			->setDescription('Listen for active update notifications for a configured external mount')
66
-			->addArgument(
67
-				'mount_id',
68
-				InputArgument::REQUIRED,
69
-				'the mount id of the mount to listen to'
70
-			)->addOption(
71
-				'user',
72
-				'u',
73
-				InputOption::VALUE_REQUIRED,
74
-				'The username for the remote mount (required only for some mount configuration that don\'t store credentials)'
75
-			)->addOption(
76
-				'password',
77
-				'p',
78
-				InputOption::VALUE_REQUIRED,
79
-				'The password for the remote mount (required only for some mount configuration that don\'t store credentials)'
80
-			)->addOption(
81
-				'path',
82
-				'',
83
-				InputOption::VALUE_REQUIRED,
84
-				'The directory in the storage to listen for updates in',
85
-				'/'
86
-			);
87
-		parent::configure();
88
-	}
62
+    protected function configure() {
63
+        $this
64
+            ->setName('files_external:notify')
65
+            ->setDescription('Listen for active update notifications for a configured external mount')
66
+            ->addArgument(
67
+                'mount_id',
68
+                InputArgument::REQUIRED,
69
+                'the mount id of the mount to listen to'
70
+            )->addOption(
71
+                'user',
72
+                'u',
73
+                InputOption::VALUE_REQUIRED,
74
+                'The username for the remote mount (required only for some mount configuration that don\'t store credentials)'
75
+            )->addOption(
76
+                'password',
77
+                'p',
78
+                InputOption::VALUE_REQUIRED,
79
+                'The password for the remote mount (required only for some mount configuration that don\'t store credentials)'
80
+            )->addOption(
81
+                'path',
82
+                '',
83
+                InputOption::VALUE_REQUIRED,
84
+                'The directory in the storage to listen for updates in',
85
+                '/'
86
+            );
87
+        parent::configure();
88
+    }
89 89
 
90
-	protected function execute(InputInterface $input, OutputInterface $output) {
91
-		$mount = $this->globalService->getStorage($input->getArgument('mount_id'));
92
-		if (is_null($mount)) {
93
-			$output->writeln('<error>Mount not found</error>');
94
-			return 1;
95
-		}
96
-		$noAuth = false;
97
-		try {
98
-			$authBackend = $mount->getAuthMechanism();
99
-			$authBackend->manipulateStorageConfig($mount);
100
-		} catch (InsufficientDataForMeaningfulAnswerException $e) {
101
-			$noAuth = true;
102
-		} catch (StorageNotAvailableException $e) {
103
-			$noAuth = true;
104
-		}
90
+    protected function execute(InputInterface $input, OutputInterface $output) {
91
+        $mount = $this->globalService->getStorage($input->getArgument('mount_id'));
92
+        if (is_null($mount)) {
93
+            $output->writeln('<error>Mount not found</error>');
94
+            return 1;
95
+        }
96
+        $noAuth = false;
97
+        try {
98
+            $authBackend = $mount->getAuthMechanism();
99
+            $authBackend->manipulateStorageConfig($mount);
100
+        } catch (InsufficientDataForMeaningfulAnswerException $e) {
101
+            $noAuth = true;
102
+        } catch (StorageNotAvailableException $e) {
103
+            $noAuth = true;
104
+        }
105 105
 
106
-		if ($input->getOption('user')) {
107
-			$mount->setBackendOption('user', $input->getOption('user'));
108
-		} else if (isset($_ENV['NOTIFY_USER'])) {
109
-			$mount->setBackendOption('user', $_ENV['NOTIFY_USER']);
110
-		} else if (isset($_SERVER['NOTIFY_USER'])) {
111
-			$mount->setBackendOption('user', $_SERVER['NOTIFY_USER']);
112
-		}
113
-		if ($input->getOption('password')) {
114
-			$mount->setBackendOption('password', $input->getOption('password'));
115
-		} else if (isset($_ENV['NOTIFY_PASSWORD'])) {
116
-			$mount->setBackendOption('password', $_ENV['NOTIFY_PASSWORD']);
117
-		} else if (isset($_SERVER['NOTIFY_PASSWORD'])) {
118
-			$mount->setBackendOption('password', $_SERVER['NOTIFY_PASSWORD']);
119
-		}
106
+        if ($input->getOption('user')) {
107
+            $mount->setBackendOption('user', $input->getOption('user'));
108
+        } else if (isset($_ENV['NOTIFY_USER'])) {
109
+            $mount->setBackendOption('user', $_ENV['NOTIFY_USER']);
110
+        } else if (isset($_SERVER['NOTIFY_USER'])) {
111
+            $mount->setBackendOption('user', $_SERVER['NOTIFY_USER']);
112
+        }
113
+        if ($input->getOption('password')) {
114
+            $mount->setBackendOption('password', $input->getOption('password'));
115
+        } else if (isset($_ENV['NOTIFY_PASSWORD'])) {
116
+            $mount->setBackendOption('password', $_ENV['NOTIFY_PASSWORD']);
117
+        } else if (isset($_SERVER['NOTIFY_PASSWORD'])) {
118
+            $mount->setBackendOption('password', $_SERVER['NOTIFY_PASSWORD']);
119
+        }
120 120
 
121
-		try {
122
-			$storage = $this->createStorage($mount);
123
-		} catch (\Exception $e) {
124
-			$output->writeln('<error>Error while trying to create storage</error>');
125
-			if ($noAuth) {
126
-				$output->writeln('<error>Username and/or password required</error>');
127
-			}
128
-			return 1;
129
-		}
130
-		if (!$storage instanceof INotifyStorage) {
131
-			$output->writeln('<error>Mount of type "' . $mount->getBackend()->getText() . '" does not support active update notifications</error>');
132
-			return 1;
133
-		}
121
+        try {
122
+            $storage = $this->createStorage($mount);
123
+        } catch (\Exception $e) {
124
+            $output->writeln('<error>Error while trying to create storage</error>');
125
+            if ($noAuth) {
126
+                $output->writeln('<error>Username and/or password required</error>');
127
+            }
128
+            return 1;
129
+        }
130
+        if (!$storage instanceof INotifyStorage) {
131
+            $output->writeln('<error>Mount of type "' . $mount->getBackend()->getText() . '" does not support active update notifications</error>');
132
+            return 1;
133
+        }
134 134
 
135
-		$verbose = $input->getOption('verbose');
135
+        $verbose = $input->getOption('verbose');
136 136
 
137
-		$path = trim($input->getOption('path'), '/');
138
-		$notifyHandler = $storage->notify($path);
139
-		$this->selfTest($storage, $notifyHandler, $verbose, $output);
140
-		$notifyHandler->listen(function (IChange $change) use ($mount, $verbose, $output) {
141
-			if ($verbose) {
142
-				$this->logUpdate($change, $output);
143
-			}
144
-			if ($change instanceof IRenameChange) {
145
-				$this->markParentAsOutdated($mount->getId(), $change->getTargetPath(), $output);
146
-			}
147
-			$this->markParentAsOutdated($mount->getId(), $change->getPath(), $output);
148
-		});
149
-	}
137
+        $path = trim($input->getOption('path'), '/');
138
+        $notifyHandler = $storage->notify($path);
139
+        $this->selfTest($storage, $notifyHandler, $verbose, $output);
140
+        $notifyHandler->listen(function (IChange $change) use ($mount, $verbose, $output) {
141
+            if ($verbose) {
142
+                $this->logUpdate($change, $output);
143
+            }
144
+            if ($change instanceof IRenameChange) {
145
+                $this->markParentAsOutdated($mount->getId(), $change->getTargetPath(), $output);
146
+            }
147
+            $this->markParentAsOutdated($mount->getId(), $change->getPath(), $output);
148
+        });
149
+    }
150 150
 
151
-	private function createStorage(StorageConfig $mount) {
152
-		$class = $mount->getBackend()->getStorageClass();
153
-		return new $class($mount->getBackendOptions());
154
-	}
151
+    private function createStorage(StorageConfig $mount) {
152
+        $class = $mount->getBackend()->getStorageClass();
153
+        return new $class($mount->getBackendOptions());
154
+    }
155 155
 
156
-	private function markParentAsOutdated($mountId, $path, OutputInterface $output) {
157
-		$parent = ltrim(dirname($path), '/');
158
-		if ($parent === '.') {
159
-			$parent = '';
160
-		}
156
+    private function markParentAsOutdated($mountId, $path, OutputInterface $output) {
157
+        $parent = ltrim(dirname($path), '/');
158
+        if ($parent === '.') {
159
+            $parent = '';
160
+        }
161 161
 
162
-		try {
163
-			$storageIds = $this->getStorageIds($mountId);
164
-		} catch (DriverException $ex) {
165
-			$this->logger->logException($ex, ['message' => 'Error while trying to find correct storage ids.', 'level' => ILogger::WARN]);
166
-			$this->connection = $this->reconnectToDatabase($this->connection, $output);
167
-			$output->writeln('<info>Needed to reconnect to the database</info>');
168
-			$storageIds = $this->getStorageIds($mountId);
169
-		}
170
-		if (count($storageIds) === 0) {
171
-			throw new StorageNotAvailableException('No storages found by mount ID ' . $mountId);
172
-		}
173
-		$storageIds = array_map('intval', $storageIds);
162
+        try {
163
+            $storageIds = $this->getStorageIds($mountId);
164
+        } catch (DriverException $ex) {
165
+            $this->logger->logException($ex, ['message' => 'Error while trying to find correct storage ids.', 'level' => ILogger::WARN]);
166
+            $this->connection = $this->reconnectToDatabase($this->connection, $output);
167
+            $output->writeln('<info>Needed to reconnect to the database</info>');
168
+            $storageIds = $this->getStorageIds($mountId);
169
+        }
170
+        if (count($storageIds) === 0) {
171
+            throw new StorageNotAvailableException('No storages found by mount ID ' . $mountId);
172
+        }
173
+        $storageIds = array_map('intval', $storageIds);
174 174
 
175
-		$result = $this->updateParent($storageIds, $parent);
176
-		if ($result === 0) {
177
-			//TODO: Find existing parent further up the tree in the database and register that folder instead.
178
-			$this->logger->info('Failed updating parent for "' . $path . '" while trying to register change. It may not exist in the filecache.');
179
-		}
180
-	}
175
+        $result = $this->updateParent($storageIds, $parent);
176
+        if ($result === 0) {
177
+            //TODO: Find existing parent further up the tree in the database and register that folder instead.
178
+            $this->logger->info('Failed updating parent for "' . $path . '" while trying to register change. It may not exist in the filecache.');
179
+        }
180
+    }
181 181
 
182
-	private function logUpdate(IChange $change, OutputInterface $output) {
183
-		switch ($change->getType()) {
184
-			case INotifyStorage::NOTIFY_ADDED:
185
-				$text = 'added';
186
-				break;
187
-			case INotifyStorage::NOTIFY_MODIFIED:
188
-				$text = 'modified';
189
-				break;
190
-			case INotifyStorage::NOTIFY_REMOVED:
191
-				$text = 'removed';
192
-				break;
193
-			case INotifyStorage::NOTIFY_RENAMED:
194
-				$text = 'renamed';
195
-				break;
196
-			default:
197
-				return;
198
-		}
182
+    private function logUpdate(IChange $change, OutputInterface $output) {
183
+        switch ($change->getType()) {
184
+            case INotifyStorage::NOTIFY_ADDED:
185
+                $text = 'added';
186
+                break;
187
+            case INotifyStorage::NOTIFY_MODIFIED:
188
+                $text = 'modified';
189
+                break;
190
+            case INotifyStorage::NOTIFY_REMOVED:
191
+                $text = 'removed';
192
+                break;
193
+            case INotifyStorage::NOTIFY_RENAMED:
194
+                $text = 'renamed';
195
+                break;
196
+            default:
197
+                return;
198
+        }
199 199
 
200
-		$text .= ' ' . $change->getPath();
201
-		if ($change instanceof IRenameChange) {
202
-			$text .= ' to ' . $change->getTargetPath();
203
-		}
200
+        $text .= ' ' . $change->getPath();
201
+        if ($change instanceof IRenameChange) {
202
+            $text .= ' to ' . $change->getTargetPath();
203
+        }
204 204
 
205
-		$output->writeln($text);
206
-	}
205
+        $output->writeln($text);
206
+    }
207 207
 
208
-	/**
209
-	 * @param int $mountId
210
-	 * @return array
211
-	*/
212
-	private function getStorageIds($mountId) {
213
-		$qb = $this->connection->getQueryBuilder();
214
-		return $qb
215
-			->select('storage_id')
216
-			->from('mounts')
217
-			->where($qb->expr()->eq('mount_id', $qb->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
218
-			->execute()
219
-			->fetchAll(\PDO::FETCH_COLUMN);
220
-	}
208
+    /**
209
+     * @param int $mountId
210
+     * @return array
211
+     */
212
+    private function getStorageIds($mountId) {
213
+        $qb = $this->connection->getQueryBuilder();
214
+        return $qb
215
+            ->select('storage_id')
216
+            ->from('mounts')
217
+            ->where($qb->expr()->eq('mount_id', $qb->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
218
+            ->execute()
219
+            ->fetchAll(\PDO::FETCH_COLUMN);
220
+    }
221 221
 
222
-	/**
223
-	 * @param array $storageIds
224
-	 * @param string $parent
225
-	 * @return int
226
-	*/
227
-	private function updateParent($storageIds, $parent) {
228
-		$pathHash = md5(trim(\OC_Util::normalizeUnicode($parent), '/'));
229
-		$qb = $this->connection->getQueryBuilder();
230
-		return $qb
231
-			->update('filecache')
232
-			->set('size', $qb->createNamedParameter(-1, IQueryBuilder::PARAM_INT))
233
-			->where($qb->expr()->in('storage', $qb->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY, ':storage_ids')))
234
-			->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
235
-			->execute();
236
-	}
222
+    /**
223
+     * @param array $storageIds
224
+     * @param string $parent
225
+     * @return int
226
+     */
227
+    private function updateParent($storageIds, $parent) {
228
+        $pathHash = md5(trim(\OC_Util::normalizeUnicode($parent), '/'));
229
+        $qb = $this->connection->getQueryBuilder();
230
+        return $qb
231
+            ->update('filecache')
232
+            ->set('size', $qb->createNamedParameter(-1, IQueryBuilder::PARAM_INT))
233
+            ->where($qb->expr()->in('storage', $qb->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY, ':storage_ids')))
234
+            ->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
235
+            ->execute();
236
+    }
237 237
 
238
-	/**
239
-	 * @return \OCP\IDBConnection
240
-	*/
241
-	private function reconnectToDatabase(IDBConnection $connection, OutputInterface $output) {
242
-		try {
243
-			$connection->close();
244
-		} catch (\Exception $ex) {
245
-			$this->logger->logException($ex, ['app' => 'files_external', 'message' => 'Error while disconnecting from DB', 'level' => ILogger::WARN]);
246
-			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
247
-		}
248
-		while (!$connection->isConnected()) {
249
-			try {
250
-				$connection->connect();
251
-			} catch (\Exception $ex) {
252
-				$this->logger->logException($ex, ['app' => 'files_external', 'message' => 'Error while re-connecting to database', 'level' => ILogger::WARN]);
253
-				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
254
-				sleep(60);
255
-			}
256
-		}
257
-		return $connection;
258
-	}
238
+    /**
239
+     * @return \OCP\IDBConnection
240
+     */
241
+    private function reconnectToDatabase(IDBConnection $connection, OutputInterface $output) {
242
+        try {
243
+            $connection->close();
244
+        } catch (\Exception $ex) {
245
+            $this->logger->logException($ex, ['app' => 'files_external', 'message' => 'Error while disconnecting from DB', 'level' => ILogger::WARN]);
246
+            $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
247
+        }
248
+        while (!$connection->isConnected()) {
249
+            try {
250
+                $connection->connect();
251
+            } catch (\Exception $ex) {
252
+                $this->logger->logException($ex, ['app' => 'files_external', 'message' => 'Error while re-connecting to database', 'level' => ILogger::WARN]);
253
+                $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
254
+                sleep(60);
255
+            }
256
+        }
257
+        return $connection;
258
+    }
259 259
 
260 260
 
261
-	private function selfTest(IStorage $storage, INotifyHandler $notifyHandler, $verbose, OutputInterface $output) {
262
-		usleep(100 * 1000); //give time for the notify to start
263
-		$storage->file_put_contents('/.nc_test_file.txt', 'test content');
264
-		$storage->mkdir('/.nc_test_folder');
265
-		$storage->file_put_contents('/.nc_test_folder/subfile.txt', 'test content');
261
+    private function selfTest(IStorage $storage, INotifyHandler $notifyHandler, $verbose, OutputInterface $output) {
262
+        usleep(100 * 1000); //give time for the notify to start
263
+        $storage->file_put_contents('/.nc_test_file.txt', 'test content');
264
+        $storage->mkdir('/.nc_test_folder');
265
+        $storage->file_put_contents('/.nc_test_folder/subfile.txt', 'test content');
266 266
 
267
-		usleep(100 * 1000); //time for all changes to be processed
268
-		$changes = $notifyHandler->getChanges();
267
+        usleep(100 * 1000); //time for all changes to be processed
268
+        $changes = $notifyHandler->getChanges();
269 269
 
270
-		$storage->unlink('/.nc_test_file.txt');
271
-		$storage->unlink('/.nc_test_folder/subfile.txt');
272
-		$storage->rmdir('/.nc_test_folder');
270
+        $storage->unlink('/.nc_test_file.txt');
271
+        $storage->unlink('/.nc_test_folder/subfile.txt');
272
+        $storage->rmdir('/.nc_test_folder');
273 273
 
274
-		usleep(100 * 1000); //time for all changes to be processed
275
-		$notifyHandler->getChanges(); // flush
274
+        usleep(100 * 1000); //time for all changes to be processed
275
+        $notifyHandler->getChanges(); // flush
276 276
 
277
-		$foundRootChange = false;
278
-		$foundSubfolderChange = false;
277
+        $foundRootChange = false;
278
+        $foundSubfolderChange = false;
279 279
 
280
-		foreach ($changes as $change) {
281
-			if ($change->getPath() === '/.nc_test_file.txt' || $change->getPath() === '.nc_test_file.txt') {
282
-				$foundRootChange = true;
283
-			} else if ($change->getPath() === '/.nc_test_folder/subfile.txt' || $change->getPath() === '.nc_test_folder/subfile.txt') {
284
-				$foundSubfolderChange = true;
285
-			}
286
-		}
280
+        foreach ($changes as $change) {
281
+            if ($change->getPath() === '/.nc_test_file.txt' || $change->getPath() === '.nc_test_file.txt') {
282
+                $foundRootChange = true;
283
+            } else if ($change->getPath() === '/.nc_test_folder/subfile.txt' || $change->getPath() === '.nc_test_folder/subfile.txt') {
284
+                $foundSubfolderChange = true;
285
+            }
286
+        }
287 287
 
288
-		if ($foundRootChange && $foundSubfolderChange && $verbose) {
289
-			$output->writeln('<info>Self-test successful</info>');
290
-		} else if ($foundRootChange && !$foundSubfolderChange) {
291
-			$output->writeln('<error>Error while running self-test, change is subfolder not detected</error>');
292
-		} else if (!$foundRootChange) {
293
-			$output->writeln('<error>Error while running self-test, no changes detected</error>');
294
-		}
295
-	}
288
+        if ($foundRootChange && $foundSubfolderChange && $verbose) {
289
+            $output->writeln('<info>Self-test successful</info>');
290
+        } else if ($foundRootChange && !$foundSubfolderChange) {
291
+            $output->writeln('<error>Error while running self-test, change is subfolder not detected</error>');
292
+        } else if (!$foundRootChange) {
293
+            $output->writeln('<error>Error while running self-test, no changes detected</error>');
294
+        }
295
+    }
296 296
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 			return 1;
129 129
 		}
130 130
 		if (!$storage instanceof INotifyStorage) {
131
-			$output->writeln('<error>Mount of type "' . $mount->getBackend()->getText() . '" does not support active update notifications</error>');
131
+			$output->writeln('<error>Mount of type "'.$mount->getBackend()->getText().'" does not support active update notifications</error>');
132 132
 			return 1;
133 133
 		}
134 134
 
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 		$path = trim($input->getOption('path'), '/');
138 138
 		$notifyHandler = $storage->notify($path);
139 139
 		$this->selfTest($storage, $notifyHandler, $verbose, $output);
140
-		$notifyHandler->listen(function (IChange $change) use ($mount, $verbose, $output) {
140
+		$notifyHandler->listen(function(IChange $change) use ($mount, $verbose, $output) {
141 141
 			if ($verbose) {
142 142
 				$this->logUpdate($change, $output);
143 143
 			}
@@ -168,14 +168,14 @@  discard block
 block discarded – undo
168 168
 			$storageIds = $this->getStorageIds($mountId);
169 169
 		}
170 170
 		if (count($storageIds) === 0) {
171
-			throw new StorageNotAvailableException('No storages found by mount ID ' . $mountId);
171
+			throw new StorageNotAvailableException('No storages found by mount ID '.$mountId);
172 172
 		}
173 173
 		$storageIds = array_map('intval', $storageIds);
174 174
 
175 175
 		$result = $this->updateParent($storageIds, $parent);
176 176
 		if ($result === 0) {
177 177
 			//TODO: Find existing parent further up the tree in the database and register that folder instead.
178
-			$this->logger->info('Failed updating parent for "' . $path . '" while trying to register change. It may not exist in the filecache.');
178
+			$this->logger->info('Failed updating parent for "'.$path.'" while trying to register change. It may not exist in the filecache.');
179 179
 		}
180 180
 	}
181 181
 
@@ -197,9 +197,9 @@  discard block
 block discarded – undo
197 197
 				return;
198 198
 		}
199 199
 
200
-		$text .= ' ' . $change->getPath();
200
+		$text .= ' '.$change->getPath();
201 201
 		if ($change instanceof IRenameChange) {
202
-			$text .= ' to ' . $change->getTargetPath();
202
+			$text .= ' to '.$change->getTargetPath();
203 203
 		}
204 204
 
205 205
 		$output->writeln($text);
Please login to merge, or discard this patch.