This repository has been archived by the owner on Jul 10, 2023. It is now read-only.
forked from sciencemesh/nc-sciencemesh
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathRevaController.php
1041 lines (951 loc) · 30 KB
/
RevaController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace OCA\ScienceMesh\Controller;
use OCA\ScienceMesh\ServerConfig;
use OCA\ScienceMesh\PlainResponse;
use OCA\ScienceMesh\ResourceServer;
use OCA\ScienceMesh\NextcloudAdapter;
use OCA\Files_Trashbin\Trash\ITrashManager;
use OCP\IRequest;
use OCP\IUserManager;
use OCP\IGroupManager;
use OCP\IURLGenerator;
use OCP\ISession;
use OCP\IConfig;
use OCP\Files\IRootFolder;
use OCP\Files\IHomeStorage;
use OCP\Files\SimpleFS\ISimpleRoot;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\TextPlainResponse;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\AppFramework\Controller;
use OCA\CloudFederationAPI\Config;
use OCP\Federation\Exceptions\ActionNotSupportedException;
use OCP\Federation\Exceptions\AuthenticationFailedException;
use OCP\Federation\Exceptions\BadRequestException;
use OCP\Federation\Exceptions\ProviderCouldNotAddShareException;
use OCP\Federation\Exceptions\ProviderDoesNotExistsException;
use OCP\Federation\ICloudFederationFactory;
use OCP\Federation\ICloudFederationProviderManager;
use OCP\Federation\ICloudIdManager;
use OCP\Share\IManager;
use OCP\Share\IShare;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Constants;
use Psr\Log\LoggerInterface;
class RevaController extends Controller {
/* @var ISession */
private $session;
/** @var LoggerInterface */
private $logger;
/** @var IUserManager */
private $userManager;
/** @var IGroupManager */
private $groupManager;
/** @var IURLGenerator */
private $urlGenerator;
/** @var ICloudFederationProviderManager */
private $cloudFederationProviderManager;
/** @var Config */
private $config;
/** @var ICloudFederationFactory */
private $factory;
/** @var ICloudIdManager */
private $cloudIdManager;
# UserService : unused
public function __construct(
$AppName,
IRootFolder $rootFolder,
IRequest $request,
ISession $session,
IUserManager $userManager,
IURLGenerator $urlGenerator,
$userId,
IConfig $config,
\OCA\ScienceMesh\Service\UserService $UserService,
ITrashManager $trashManager,
IManager $shareManager,
IGroupManager $groupManager,
ICloudFederationProviderManager $cloudFederationProviderManager,
ICloudFederationFactory $factory,
ICloudIdManager $cloudIdManager,
LoggerInterface $logger
)
{
parent::__construct($AppName, $request);
require_once(__DIR__.'/../../vendor/autoload.php');
$this->config = new \OCA\ScienceMesh\ServerConfig($config, $urlGenerator, $userManager);
$this->rootFolder = $rootFolder;
$this->request = $request;
$this->urlGenerator = $urlGenerator;
$this->session = $session;
$this->userManager = $userManager;
$this->trashManager = $trashManager;
$this->userFolder = $this->rootFolder->getUserFolder($userId);
// Create the Nextcloud Adapter
$adapter = new NextcloudAdapter($this->userFolder);
$this->filesystem = new \League\Flysystem\Filesystem($adapter);
$this->baseUrl = $this->getStorageUrl($userId); // Where is that used?
# Share
$this->shareManager = $shareManager;
$this->logger = $logger;
$this->groupManager = $groupManager;
$this->cloudFederationProviderManager = $cloudFederationProviderManager;
$this->factory = $factory;
$this->cloudIdManager = $cloudIdManager;
}
/**
* @param array $nodeInfo
*
* Returns the data of a CS3 provider.ResourceInfo object https://github.com/cs3org/cs3apis/blob/a86e5cb/cs3/storage/provider/v1beta1/resources.proto#L35-L93
* @return array
*
* @throws \OCP\Files\InvalidPathException
* @throws \OCP\Files\NotFoundException
*/
private function nodeInfoToCS3ResourceInfo(array $nodeInfo) : array
{
$path = substr($nodeInfo["path"], strlen("/sciencemesh"));
$isDirectory = ($nodeInfo["mimetype"] == "directory");
return [
"opaque" => [
"map" => NULL,
],
"type" => ($isDirectory ? 2 : 1),
"id" => [
"opaque_id" => "fileid-/" . $path,
],
"checksum" => [
"type" => 0,
"sum" => "",
],
"etag" => "deadbeef",
"mime_type" => $nodeInfo["mimetype"],
"mtime" => [
"seconds" => 1234567890
],
"path" => "/" . $path,
"permission_set" => [
"add_grant" => false,
"create_container" => false,
"delete" => false,
"get_path" => false,
"get_quota" => false,
"initiate_file_download" => false,
"initiate_file_upload" => false,
// "listGrants => false,
// "listContainer => false,
// "listFileVersions => false,
// "listRecycle => false,
// "move => false,
// "removeGrant => false,
// "purgeRecycle => false,
// "restoreFileVersion => false,
// "restoreRecycleItem => false,
// "stat => false,
// "updateGrant => false,
// "denyGrant => false,
],
"size" => 12345,
"canonical_metadata" => [
"target" => NULL,
],
"arbitrary_metadata" => [
"metadata" => [
"some" => "arbi",
"trary" => "meta",
"da" => "ta",
],
],
"owner" => [
"opaque_id" => "f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c",
],
];
}
# For ListReceivedShares, GetReceivedShare and UpdateReceivedShare we need to include "state:2"
private function shareInfoToResourceInfo(IShare $share): array
{
return [
"id"=>[
"map" => NULL,
],
"resource_id"=>[
"map" => NULL,
],
"permissions"=>[
"permissions"=>[
"add_grant"=>true,
"create_container"=>true,
"delete"=>true,
"get_path"=>true,
"get_quota"=>true,
"initiate_file_download"=>true,
"initiate_file_upload"=>true,
"list_grants"=>true,
"list_container"=>true,
"list_file_versions"=>true,
"list_recycle"=>true,
"move"=>true,
"remove_grant"=>true,
"purge_recycle"=>true,
"restore_file_version"=>true,
"restore_recycle_item"=>true,
"stat"=>true,
"update_grant"=>true,
"deny_grant"=>true
]
],
"grantee"=>[
"Id"=>[
"UserId"=>[
"idp"=>"0.0.0.0:19000",
"opaque_id"=>"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c",
"type"=>1
]
]
],
"owner"=>[
"idp"=>"0::.0.0.0:19000",
"opaque_id"=>"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c",
"type"=>1
],
"creator"=>[
"idp"=>"0.0.0.0:19000",
"opaque_id"=>"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c",
"type"=>1
],
"ctime"=>[
"seconds"=>1234567890
],
"mtime"=>[
"seconds"=>1234567890
]
];
}
# correspondes the permissions we got from Reva to Nextcloud
private function getPermissionsCode(array $permissions) : int
{
$permissionsCode = 0;
if(!empty($permissions["get_path"]) || !empty($permissions["get_quota"]) || !empty($permissions["initiate_file_download"]) || !empty($permissions["initiate_file_upload"]) || !empty($permissions["stat"]) ){
$permissionsCode += \OCP\Constants::PERMISSION_READ;
}
if( !empty($permissions["create_container"]) || !empty($permissions["move"]) || !empty($permissions["add_grant"]) || !empty($permissions["restore_file_version"]) || !empty($permissions["restore_recycle_item"]) ){
$permissionsCode += \OCP\Constants::PERMISSION_CREATE;
}
if( !empty($permissions["move"]) || !empty($permissions["delete"]) || !empty($permissions["remove_grant"])){
$permissionsCode += \OCP\Constants::PERMISSION_DELETE;
}
if( !empty($permissions["list_grants"]) || !empty($permissions["list_file_versions"]) || !empty($permissions["list_recycle"])){
$permissionsCode += \OCP\Constants::PERMISSION_SHARE;
}
if( !empty($permissions["update_grant"])){
$permissionsCode += \OCP\Constants::PERMISSION_UPDATE;
}
return $permissionsCode;
}
private function getShareType($granteeType){
if($granteeType == 1){
return 'user';
}
elseif($granteeType == 2){
return 'group';
}
return new JSONResponse(
['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
Http::STATUS_BAD_REQUEST
);
}
/**
* @param int
*
* @return int
* @throws NotFoundException
*/
private function getStorageUrl($userId) {
$storageUrl = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute("sciencemesh.storage.handleHead", array("userId" => $userId, "path" => "foo")));
$storageUrl = preg_replace('/foo$/', '', $storageUrl);
return $storageUrl;
}
private function respond($responseBody, $statusCode, $headers=array()) {
$result = new PlainResponse($body);
foreach ($headers as $header => $values) {
foreach ($values as $value) {
$result->addHeader($header, $value);
}
}
$result->setStatus($statusCode);
return $result;
}
/* Reva handlers */
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function AddGrant($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
// FIXME: Expected a param with a grant to add here;
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function Authenticate($userId) {
$password = $this->request->getParam("password");
// Try e.g.:
// curl -v -H 'Content-Type:application/json' -d'{"password":"relativity"}' http://localhost/apps/sciencemesh/~einstein/api/Authenticate
// FIXME: https://github.com/pondersource/nc-sciencemesh/issues/3
$auth = $this->userManager->checkPassword($userId,$password);
if ($auth) {
return new JSONResponse("Logged in", 200);
}
return new JSONResponse("Username / password not recognized", 401);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function CreateDir($userId) {
$path = "sciencemesh" . $this->request->getParam("path"); // FIXME: sanitize the input
$success = $this->filesystem->createDir($path);
if ($success) {
return new JSONResponse("OK", 200);
}
return new JSONResponse(["error" => "Could not create directory."], 500);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function CreateHome($userId) {
error_log('userid: '.$userId);
$homeExists = $this->userFolder->nodeExists("sciencemesh");
if (!$homeExists) {
$this->userFolder->newFolder("sciencemesh"); // Create the Sciencemesh directory for storage if it doesn't exist.
}
return new JSONResponse("OK", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function CreateReference($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: normalize incoming path
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function Delete($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: normalize incoming path
$success = $this->filesystem->delete($path);
if ($success) {
return new JSONResponse("OK", 200);
}
return new JSONResponse(["error" => "Failed to delete."], 500);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function EmptyRecycle($userId) {
$user = $this->userManager->get($userId);
$trashItems = $this->trashManager->listTrashRoot($user);
$result = []; // Where is this used?
foreach ($trashItems as $node) {
#getOriginalLocation : returns string
if (preg_match("/^sciencemesh/", $node->getOriginalLocation())) {
$this->trashManager->removeItem($node);
}
}
return new JSONResponse("OK", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function GetMD($userId) {
$ref = $this->request->getParam("ref");
$path = "sciencemesh" . $ref["path"]; // FIXME: normalize incoming path
$success = $this->filesystem->has($path);
if ($success) {
$nodeInfo = $this->filesystem->getMetaData($path);
$resourceInfo = $this->nodeInfoToCS3ResourceInfo($nodeInfo);
return new JSONResponse($resourceInfo, 200);
}
return new JSONResponse(["error" => "File not found"], 404);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function GetPathByID($userId) {
// in progress
$path = "subdir/";
$storageId = $this->request->getParam("storage_id");
$opaqueId = $this->request->getParam("opaque_id");
return new TextPlainResponse($path, 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function InitiateUpload($userId) {
$response = [
"simple" => "yes",
"tus" => "yes" // FIXME: Not really supporting this;
];
return new JSONResponse($response, 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function ListFolder($userId) {
$ref = $this->request->getParam("ref");
$path = "sciencemesh" . $ref["path"]; // FIXME: sanitize!
$success = $this->filesystem->has($path);
if(!$success){
return new JSONResponse(["error" => "Folder not found"], 404);
}
$nodeInfos = $this->filesystem->listContents($path);
$resourceInfos = array_map(function($nodeInfo) {
return $this->nodeInfoToCS3ResourceInfo($nodeInfo);
}, $nodeInfos);
return new JSONResponse($resourceInfos, 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function ListGrants($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function ListRecycle($userId) {
$user = $this->userManager->get($userId);
$trashItems = $this->trashManager->listTrashRoot($user);
$result = [];
foreach ($trashItems as $node) {
if (preg_match("/^sciencemesh/", $node->getOriginalLocation())) {
$path = substr($node->getOriginalLocation(), strlen("sciencemesh"));
$result = [
[
"opaque" => [
"map" => NULL,
],
"key" => $path,
"ref" => [
"resource_id" => [
"map" => NULL,
],
"path" => $path,
],
"size" => 12345,
"deletion_time" => [
"seconds" => 1234567890
]
]];
}
}
return new JSONResponse($result, 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function ListRevisions($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function Move($userId) {
$from = $this->request->getParam("from");
$to = $this->request->getParam("to");
$success = $this->filesystem->move($from, $to);
if ($success) {
return new JSONResponse("OK", 200);
}
return new JSONResponse(["error" => "Failed to move."], 500);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function RemoveGrant($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
// FIXME: Expected a grant to remove here;
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
//{"key":"some-deleted-version","path":"/","restoreRef":{"path":"/subdirRestored"}}`:
//{200, ``, serverStateFileRestored},
//{"key":"some-deleted-version","path":"/","restoreRef":null}`:
//{200, ``, serverStateFileRestored},
public function RestoreRecycleItem($userId) {
$key = $this->request->getParam("key");
$user = $this->userManager->get($userId);
$trashItems = $this->trashManager->listTrashRoot($user);
foreach ($trashItems as $node) {
if (preg_match("/^sciencemesh/", $node->getOriginalLocation())) {
// we are using original location as the RecycleItem's
// unique key string, see:
// https://github.com/cs3org/cs3apis/blob/6eab4643f5113a54f4ce4cd8cb462685d0cdd2ef/cs3/storage/provider/v1beta1/resources.proto#L318
if ("sciencemesh" . $key == $node->getOriginalLocation()) {
$this->trashManager->restoreItem($node);
return new JSONResponse("OK", 200);
}
}
}
return new JSONResponse('["error" => "Not found."]', 404);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function RestoreRevision($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
// FIXME: Expected a revision param here;
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function SetArbitraryMetadata($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
$metadata = $this->request->getParam("metadata");
// FIXME: What do we do with the existing metadata? Just toss it and overwrite with the new value? Or do we merge?
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function UnsetArbitraryMetadata($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function UpdateGrant($userId) {
$path = "sciencemesh" . $this->request->getParam("path") ?: "/"; // FIXME: sanitize
// FIXME: Expected a paramater with the grant(s)
return new JSONResponse("Not implemented", 200);
}
/**
* @PublicPage
* @NoAdminRequired
* @NoCSRFRequired
*/
public function Upload($userId, $path) {
$contents = $this->request->put;
if ($this->filesystem->has("/sciencemesh" . $path)) {
$success = $this->filesystem->update("/sciencemesh" . $path, $contents);
if ($success) {
return new JSONResponse("OK", 200);
} else {
return new JSONResponse(["error" => "Update failed"], 500);
}
}
$success = $this->filesystem->write("/sciencemesh" . $path, $contents);
if ($success) {
return new JSONResponse("OK", 201);
}
return new JSONResponse(["error" => "Create failed"], 500);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* Create a new share in fn with the given access control list.
*/
// {
// "md":{
// "opaque_id":"fileid-/some/path"
// },
// "g":{
// "grantee":{
// "Id":{
// "UserId":{
// "idp":"0.0.0.0:19000",
// "opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c",
// "type":1
// }
// }
// },
// "permissions":{
// "permissions":{}
// }
// }
// }
public function Share($userId){
$md = $this->request->getParam("md");
$g = $this->request->getParam("g");
$opaqueId = $md["opaque_id"];
$opaqueId = str_replace('fileid-', 'sciencemesh', $opaqueId);
$grantee = $g["grantee"];
$granteeId = $grantee["Id"];
$granteeIdUserId = $granteeId["UserId"];
// $shareWith = $granteeIdUserId["opaque_id"]."@".$granteeIdUserId["idp"];
$sharePermissions = $g["permissions"];
$resourcePermissions = $sharePermissions["permissions"];
$permissionsCode = $this->getPermissionsCode($resourcePermissions);
//$shareWith = "einstein@localhost:8080";
$shareWith = "[email protected]";
$share = $this->shareManager->newShare();
$share->setPermissions($permissionsCode);
$share->setShareType(IShare::TYPE_REMOTE);
$share->setSharedBy($userId);
try {
$path = $this->userFolder->get($opaqueId);
} catch (NotFoundException $e) {
return new JSONResponse(["error" => "Share failed. Resource Path not found"], 500);
}
$share->setNode($path);
try {
$share->setSharedWith($shareWith);
} catch (InvalidArgumentException $e) {
return new JSONResponse(["error" => "Share failed. Invalid share receipient"], 500);}
$this->shareManager->createShare($share);
$response = $this->shareInfoToResourceInfo($share);
return new JSONResponse($response, 201);
}
/**
* add share
*
* @NoCSRFRequired
* @PublicPage
* @BruteForceProtection(action=receiveFederatedShare)
*
* @param string $shareWith
* @param string $name resource name (e.g. document.odt)
* @param string $description share description (optional)
* @param string $providerId resource UID on the provider side
* @param string $owner provider specific UID of the user who owns the resource
* @param string $ownerDisplayName display name of the user who shared the item
* @param string $sharedBy provider specific UID of the user who shared the resource
* @param string $sharedByDisplayName display name of the user who shared the resource
* @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
* @param string $shareType ('group' or 'user' share)
* @param $resourceType ('file', 'calendar',...)
* @return Http\DataResponse|JSONResponse
*
* Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
*/
// public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
public function addShare($userId) {
$md = $this->request->getParam("md");
$g = $this->request->getParam("g");
$opaqueId = $md["opaque_id"];
$opaqueIdDecoded = urldecode($opaqueId);
$opaqueIdExploded = explode("/",$opaqueIdDecoded);
$ownerName =substr($opaqueIdExploded[0],strlen("fileid-"));
$sharedBy = $owner;
$ownerDisplayName = 'Albert Einstein';
$sharedByDisplayName = '';
$description = '';
$grantee = $g["grantee"];
$granteeId = $grantee["Id"];
$granteeIdUserId = $granteeId["UserId"];
//$shareWith = $granteeIdUserId["opaque_id"]."@".$granteeIdUserId["idp"]; //OK the huge number is for reva not nextcloud
$sharePermissions = $g["permissions"];
$resourcePermissions = $sharePermissions["permissions"];
$permissionsCode = $this->getPermissionsCode($resourcePermissions); // maybe unused
$protocol = [
'name'=>'webdav',
'options'=>[
"sharedSecret"=>"secret",
"permissions"=>"webdav-property",
]
];
$shareWith = '[email protected]';
$name = end($opaqueIdExploded);
$providerId = 2;
$owner = "[email protected]";
$resourceType = 'file';
$shareType = $this->getShareType($grantee["type"]);
error_log("shareWith: ".$shareWith. " HARDCODED");
error_log('name: '.$name);
error_log("providerId: ".$providerId." HARDCODED");
error_log("owner: ".$owner. " HARDCODED");
error_log("resourceType: ".$resourceType. " HARDCODED");
error_log("shareType: ".$shareType);
// check if all required parameters are set
if ($shareWith === null || // hardcoded
$name === null || // ok
$providerId === null || // ok
$owner === null || // hardcoded
$resourceType === null || // hardcoded
$shareType === null || // ok
!is_array($protocol) ||
!isset($protocol['name']) ||
!isset($protocol['options']) ||
!is_array($protocol['options']) ||
!isset($protocol['options']['sharedSecret'])
) {
return new JSONResponse(
['message' => 'Missing arguments'],
Http::STATUS_BAD_REQUEST
);
}
$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
$shareWith = $cloudId->getUser();
if ($shareType === 'user') {
$shareWith = $this->mapUid($shareWith);
if (!$this->userManager->userExists($shareWith)) {
return new JSONResponse(
['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
Http::STATUS_BAD_REQUEST
);
}
}
if ($shareType === 'group') {
if (!$this->groupManager->groupExists($shareWith)) {
return new JSONResponse(
['message' => 'Group "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
Http::STATUS_BAD_REQUEST
);
}
}
// if no explicit display name is given, we use the uid as display name
$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
if ($sharedBy === null) {
$sharedBy = $owner;
$sharedByDisplayName = $ownerDisplayName;
}
try {
$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
$share->setProtocol($protocol);
$provider->shareReceived($share);
} catch (ProviderDoesNotExistsException $e) {
return new JSONResponse(
['message' => $e->getMessage()],
Http::STATUS_NOT_IMPLEMENTED
);
} catch (ProviderCouldNotAddShareException $e) {
return new JSONResponse(
['message' => $e->getMessage()],
$e->getCode()
);
} catch (\Exception $e) {
return new JSONResponse(
['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
Http::STATUS_BAD_REQUEST
);
}
$user = $this->userManager->get($shareWith);
$recipientDisplayName = '';
if ($user) {
$recipientDisplayName = $user->getDisplayName();
}
return new JSONResponse($response, 200);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* GetShare gets the information for a share by the given ref.
*/
public function GetShare($userId){
$spec = $this->request->getParam("Spec");
$Id = $spec["Id"];
$opaqueId = $Id["opaque_id"];
$share = $this->shareManager->getShareById($opaqueId);
if($share){
$response = $this->shareInfoToResourceInfo($share);
return new JSONResponse($response, 200);
}
return new JSONResponse(["error" => "GetShare failed"], 500);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* Unshare deletes the share pointed by ref.
*/
public function Unshare($userId){
$spec = $this->request->getParam("Spec");
$Id = $spec["Id"];
$opaqueId = $Id["opaque_id"];
$share = $this->shareManager->getShareById($opaqueId);
$success = $this->shareManager->deleteShare($share);
if ($success) {
return new JSONResponse("OK", 201);
}
return new JSONResponse(["error" => "Unshare failed"], 500);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
*/
public function UpdateShare($userId){
$ref = $this->request->getParam("ref");
$spec = $ref["Spec"];
$id = $spec["Id"];
$opaqueId = $id["opaque_id"];
$p = $this->request->getParam("p");
$permissions = $p["permissions"];
$permissionsCode = $this->getPermissionsCode($permissions);
$share = $this->shareManager->getShareById($opaqueId);
$updated = $this->shareManager->updateShare($share, $permissionsCode);
if($updated) {
$response = $this->shareInfoToResourceInfo($updated);
return new JSONResponse($response, 201);
}
return new JSONResponse(["error" => "UpdateShare failed"], 500);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* ListShares returns the shares created by the user. If md is provided is not nil,
* it returns only shares attached to the given resource.
*/
public function ListShares($userId){
$requests = $this->request->getParams();
$request = array_values($requests)[2];
$type = $request["type"];
$term = $request["Term"];
$creator = $term["Creator"];
$idpCreator = $creator["idp"];
$opaqueIdCreator = ["opaque_id"];
$typeCreator = ["type"];
$responses = [];
$shares = $this->shareManager->getSharesBy($userId, 6);
if ($shares) {
foreach ($shares as $share) {
array_push($responses,$this->shareInfoToResourceInfo($share));
}
return new JSONResponse($responses, 201);
}
elseif($shares == []){
return new JSONResponse($shares, 200);
}
return new JSONResponse(["error" => "ListShares failed"], 500);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* ListReceivedShares returns the list of shares the user has access.
*/
public function ListReceivedShares($userId){
$responses = [];
$shares = $this->shareManager->getSharedWith($userId,IShare::TYPE_REMOTE);
if ($shares) {
foreach ($shares as $share) {
$response = $this->shareInfoToResourceInfo($share);
$response["state"] = 2;
array_push($responses, $response);
}
return new JSONResponse($responses, 201);
}
elseif($shares == []){
return new JSONResponse($shares, 200);
}
return new JSONResponse(["error" => "ListReceivedShares failed"], 500);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* GetReceivedShare returns the information for a received share the user has access.
*/
public function GetReceivedShare($userId){
$spec = $this->request->getParam("Spec");
$Id = $spec["Id"];
$opaqueId = $Id["opaque_id"];
$share = $this->shareManager->getShareById($opaqueId,$userId);
if($share) {
$response = $this->shareInfoToResourceInfo($share);
$response["state"] = 2;
return new JSONResponse($response, 201);
}
return new JSONResponse(["error" => "GetReceivedShare failed"], 500);
}