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 | "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const rxjs_1 = require("@reactivex/rxjs"); const _1 = require("../Authentication/"); const snconfigmodel_1 = require("../Config/snconfigmodel"); const Content_1 = require("../Content"); const ContentSerializer_1 = require("../ContentSerializer"); const ContentTypes_1 = require("../ContentTypes"); const ODataApi_1 = require("../ODataApi"); const Query_1 = require("../Query"); const Schemas_1 = require("../Schemas"); const SN_1 = require("../SN"); const _2 = require("./"); class BaseRepository { constructor(config, _httpProviderType, authentication) { this.Events = new _2.RepositoryEventHub(); this._loadedContentReferenceCache = []; this.CreateContent = (options, contentType) => Content_1.ContentInternal.Create(options, contentType, this); this._staticContent = { VisitorUser: this.HandleLoadedContent({ Id: 6, DisplayName: 'Visitor', Domain: 'BuiltIn', Name: 'Visitor', Path: '/Root/IMS/BuiltIn/Portal/Visitor', LoginName: 'Visitor', Type: 'User' }), PortalRoot: this.HandleLoadedContent({ Id: 2, Path: '/Root', Name: 'Root', DisplayName: 'Root', Type: 'PortalRoot' }) }; this.CreateQuery = (build, params) => new Query_1.FinializedQuery(build, this, 'Root', params); this._currentUserSubject = new rxjs_1.BehaviorSubject(this._staticContent.VisitorUser); this.GetCurrentUser = () => { return this._currentUserSubject .distinctUntilChanged() .filter((u) => { const [userDomain, userName] = this.Authentication.CurrentUser.split('\\'); return u.LoginName === userName && u.Domain === userDomain; }); }; this._lastKnownUserName = 'BuiltIn\\Visitor'; this.HttpProviderRef = new _httpProviderType(); this.Config = new snconfigmodel_1.SnConfigModel(config); this.Authentication = new authentication(this.HttpProviderRef, this.Config.RepositoryUrl, this.Config.JwtTokenKeyTemplate, this.Config.JwtTokenPersist); this._odataApi = new ODataApi_1.ODataApi(_httpProviderType, this); this.initUserUpdate(); } get ODataBaseUrl() { return SN_1.ODataHelper.joinPaths(this.Config.RepositoryUrl, this.Config.ODataToken); } WaitForAuthStateReady() { return this.Authentication.State.skipWhile((state) => state === SN_1.Authentication.LoginState.Pending) .first(); } Ajax(path, method, returnsType, body, additionalHeaders) { this.Authentication.CheckForUpdate(); return this.WaitForAuthStateReady() .flatMap((state) => { if (!returnsType) { returnsType = Object; } return this.HttpProviderRef.Ajax(returnsType, { url: SN_1.ODataHelper.joinPaths(this.ODataBaseUrl, path), method, body, responseType: 'json', }, additionalHeaders); }); } UploadFile(uploadOptions) { this.Authentication.CheckForUpdate(); uploadOptions.Body = Object.assign({}, uploadOptions.Body, { Overwrite: uploadOptions.Overwrite, PropertyName: uploadOptions.PropertyName, FileName: uploadOptions.File.name, ContentType: uploadOptions.ContentType.name }); this.Authentication.CheckForUpdate(); return this.WaitForAuthStateReady() .flatMap((state) => { const uploadSubject = new rxjs_1.Subject(); const fileName = uploadOptions.File.name; const uploadPath = SN_1.ODataHelper.joinPaths(this.ODataBaseUrl, uploadOptions.Parent.GetFullPath(), 'upload'); if (uploadOptions.File.size <= this.Config.ChunkSize) { uploadOptions.Body.ChunkToken = '0*0*False*False'; this.HttpProviderRef.Upload((uploadOptions.ContentType || Content_1.ContentInternal), uploadOptions.File, { url: uploadPath, body: uploadOptions.Body, }) .subscribe((created) => { this.HandleLoadedContent(created).Reload().subscribe((c) => { this.Events.Trigger.ContentCreated({ Content: c }); const progress = { Completed: true, ChunkCount: 1, UploadedChunks: 1, CreatedContent: c }; uploadSubject.next(progress); this.Events.Trigger.UploadProgress(progress); uploadSubject.complete(); }); }, (error) => { this.Events.Trigger.ContentCreateFailed({ Content: { Id: null, Path: null, Name: fileName }, Error: error }); uploadSubject.error(error); }); } else { const initialChunkData = uploadOptions.File.slice(0, this.Config.ChunkSize); return this.HttpProviderRef.Upload(String, new File([initialChunkData], uploadOptions.File.name), { url: uploadPath, body: Object.assign({}, uploadOptions.Body, { UseChunk: true, create: 1 }), headers: { 'Content-Range': `bytes ${0}-${this.Config.ChunkSize}/${uploadOptions.File.size}`, 'Content-Disposition': `attachment; filename="${uploadOptions.File.name}"` } }). flatMap((chunkToken) => { const resp = new _2.UploadResponse(...chunkToken.split('*')); const createdContent = this.HandleLoadedContent({ Id: resp.ContentId, Path: uploadOptions.Parent.Path, Name: uploadOptions.File.name, Type: uploadOptions.ContentType.name }); this.Events.Trigger.ContentCreated({ Content: createdContent }); return this.sendChunk(uploadOptions, uploadPath, chunkToken.toString(), resp.ContentId) .flatMap((c) => { return this.Load(resp.ContentId) .map((content) => { const chunkCount = Math.ceil(uploadOptions.File.size / this.Config.ChunkSize); content['_isOperationInProgress'] = false; const progressInfo = { Completed: true, ChunkCount: chunkCount, UploadedChunks: chunkCount, CreatedContent: content }; this.Events.Trigger.UploadProgress(progressInfo); return progressInfo; }); }); }); } return uploadSubject.asObservable(); }); } sendChunk(options, uploadPath, chunkToken, contentId, offset = 0) { this.Authentication.CheckForUpdate(); return this.WaitForAuthStateReady() .flatMap((state) => { let chunkEnd = offset + this.Config.ChunkSize; chunkEnd = chunkEnd > options.File.size ? options.File.size : chunkEnd; const chunkData = options.File.slice(offset, chunkEnd); const request = this.HttpProviderRef.Upload(Object, new File([chunkData], options.File.name), { url: uploadPath, body: Object.assign({}, options.Body, { UseChunk: true, FileLength: options.File.size, ChunkToken: chunkToken }), headers: { 'Content-Range': `bytes ${offset}-${chunkEnd - 1}/${options.File.size}`, 'Content-Disposition': `attachment; filename="${options.File.name}"` } }).map((newResp) => { const content = this.HandleLoadedContent({ Id: contentId, Path: 'asd', Name: options.File.name || 'File', Type: options.ContentType.name || 'File' }); content['_isOperationInProgress'] = true; const progress = { Completed: false, ChunkCount: Math.ceil(options.File.size / this.Config.ChunkSize), CreatedContent: content, UploadedChunks: (offset / this.Config.ChunkSize) + 1 }; this.Events.Trigger.UploadProgress(progress); return progress; }); if (chunkEnd === options.File.size) { return request; } return request.flatMap((r) => this.sendChunk(options, uploadPath, chunkToken, contentId, offset + this.Config.ChunkSize)); }); } UploadTextAsFile(options) { const file = new File([options.Text], options.FileName); return this.UploadFile(Object.assign({ File: file }, options)); } webkitFileHandler(FileEntry, Scope, options) { return __awaiter(this, void 0, void 0, function* () { yield new Promise((resolve, reject) => { FileEntry.file((f) => { Scope.UploadFile(Object.assign({ File: f }, options)) .skipWhile((progress) => !progress.Completed) .subscribe((progress) => resolve(progress), (err) => reject(err)); }, (err) => reject(err)); }); }); } webkitDirectoryHandler(Directory, Scope, options) { return __awaiter(this, void 0, void 0, function* () { yield new Promise((resolve, reject) => { this.CreateContent({ Name: Directory.name, Path: Scope.Path, DisplayName: Directory.name }, ContentTypes_1.Folder).Save().subscribe((c) => __awaiter(this, void 0, void 0, function* () { const dirReader = Directory.createReader(); yield new Promise((res) => { dirReader.readEntries((items) => __awaiter(this, void 0, void 0, function* () { yield this.webkitItemListHandler(items, c, true, options); res(); })); }); resolve(c); }), (err) => reject(err)); }); }); } webkitItemListHandler(items, Scope, CreateFolders, options) { return __awaiter(this, void 0, void 0, function* () { for (const index in items) { if (CreateFolders && items[index].isDirectory) { yield this.webkitDirectoryHandler(items[index], Scope, options); } if (items[index].isFile) { yield this.webkitFileHandler(items[index], Scope, options); } } }); } UploadFromDropEvent(options) { return __awaiter(this, void 0, void 0, function* () { if (window.webkitRequestFileSystem) { const entries = [].map.call(options.Event.dataTransfer.items, (i) => i.webkitGetAsEntry()); yield this.webkitItemListHandler(entries, options.Parent, options.CreateFolders, options); } else { [].forEach.call(options.Event.dataTransfer.files, (f) => __awaiter(this, void 0, void 0, function* () { if (f.type === 'file') { options.Parent.UploadFile(Object.assign({ File: f }, options)).subscribe((c) => { }); } })); } }); } get Content() { console.warn('The property repository.Content is deprecated and will be removed in the near future. Use repositoy.GetODataApi() instead.'); return this._odataApi; } GetODataApi() { return this._odataApi; } GetVersionInfo() { return this._odataApi.CreateCustomAction({ name: 'GetVersionInfo', path: '/Root', isAction: false }, {}, _2.VersionInfo); } GetAllContentTypes() { return this._odataApi.CreateCustomAction({ name: 'GetAllContentTypes', path: '/Root', isAction: false }, undefined, ODataApi_1.ODataCollectionResponse) .map((resp) => { return resp.d.results.map((c) => this.HandleLoadedContent(c)); }); } HandleLoadedContent(opt, contentType) { let instance; const realContentType = (contentType || (opt.Type && SN_1.ContentTypes[opt.Type]) || ContentTypes_1.Folder); if (opt.Id) { if (this._loadedContentReferenceCache[opt.Id]) { instance = this._loadedContentReferenceCache[opt.Id]; instance['updateLastSavedFields'](opt); } else { instance = Content_1.ContentInternal.Create(opt, realContentType, this); this._loadedContentReferenceCache[opt.Id] = instance; } } else { instance = Content_1.ContentInternal.Create(opt, realContentType, this); } instance['_isSaved'] = true; this.Events.Trigger.ContentLoaded({ Content: instance }); return instance; } Load(idOrPath, odataOptions, version) { const contentURL = typeof idOrPath === 'string' ? SN_1.ODataHelper.getContentURLbyPath(idOrPath) : SN_1.ODataHelper.getContentUrlbyId(idOrPath); const odataRequestOptions = { path: contentURL, params: odataOptions }; return this._odataApi.Get(odataRequestOptions) .share() .map((r) => { return this.HandleLoadedContent(r.d); }); } ParseContent(stringifiedContent) { const serializedContent = ContentSerializer_1.ContentSerializer.Parse(stringifiedContent); if (serializedContent.Origin.indexOf(this.ODataBaseUrl) !== 0) { throw new Error('Content belongs to a different Repository.'); } return this.HandleLoadedContent(serializedContent.Data); } DeleteBatch(contentList, permanent = false, rootContent = this._staticContent.PortalRoot) { const action = this._odataApi.CreateCustomAction({ name: 'DeleteBatch', path: rootContent.Path, isAction: true, requiredParams: ['paths'] }, { data: { paths: contentList.map((c) => c.Id || c.Path).filter((c) => c !== undefined), permanent } }); action.subscribe((result) => { if (result.d.__count) { result.d.results.forEach((deleted) => { this.Events.Trigger.ContentDeleted({ ContentData: deleted, Permanently: permanent }); }); result.d.errors.forEach((error) => { this.Events.Trigger.ContentDeleteFailed({ Content: this.HandleLoadedContent(error.content), Error: error.error, Permanently: permanent }); }); } }, (error) => { }); return action; } MoveBatch(contentList, targetPath, rootContent = this._staticContent.PortalRoot) { const action = this._odataApi.CreateCustomAction({ name: 'MoveBatch', path: rootContent.Path, isAction: true, requiredParams: ['targetPath', 'paths'] }, { data: [ { paths: contentList.map((c) => c.Path).filter((c) => c !== undefined), targetPath }, ] }); action.subscribe((result) => { if (result.d.__count) { result.d.results.forEach((moved) => { const from = contentList.find((a) => a.Id === moved.Id); this.Events.Trigger.ContentMoved({ From: from && from.Path || '', Content: this.HandleLoadedContent(moved), To: targetPath }); }); result.d.errors.forEach((error) => { const from = contentList.find((a) => a.Id === error.content.Id); this.Events.Trigger.ContentMoveFailed({ From: from && from.Path || '', Content: this.HandleLoadedContent(error.content), To: targetPath, Error: error.error }); }); } }, (error) => { }); return action; } CopyBatch(contentList, targetPath, rootContent = this._staticContent.PortalRoot) { const action = this._odataApi.CreateCustomAction({ name: 'CopyBatch', path: rootContent.Path, isAction: true, requiredParams: ['targetPath', 'paths'] }, { data: [ { paths: contentList.map((c) => c.Path).filter((c) => c !== undefined), targetPath }, ] }); action.subscribe((result) => { if (result.d.__count) { result.d.results.forEach((created) => { this.Events.Trigger.ContentCreated({ Content: this.HandleLoadedContent(created) }); }); result.d.errors.forEach((error) => { this.Events.Trigger.ContentCreateFailed({ Content: error.content, Error: error.error }); }); } }, (error) => { }); return action; } initUserUpdate() { this.Authentication.State.skipWhile((state) => state === SN_1.Authentication.LoginState.Pending) .subscribe((state) => { if (state === _1.LoginState.Unauthenticated) { this._currentUserSubject.next(this._staticContent.VisitorUser); this._lastKnownUserName = 'BuiltIn\\Visitor'; } else { if (this._lastKnownUserName !== this.Authentication.CurrentUser) { const [userDomain, userName] = this.Authentication.CurrentUser.split('\\'); this.CreateQuery((q) => q.TypeIs(ContentTypes_1.User) .And .Equals('Domain', userDomain) .And .Equals('LoginName', userName) .Top(1), { select: 'all' }).Exec() .subscribe((usr) => { if (usr.Count === 1) { this._currentUserSubject.next(usr.Result[0]); this._lastKnownUserName = this.Authentication.CurrentUser; } else { this._currentUserSubject.error(`Error getting current user: found multiple users with login name '${userName}' in domain '${userDomain}'`); } }); } } }); } GetSchema(currentType) { if (!this._schemaCache) { this._schemaCache = new Map(); } if (!this._schemaStore) { this._schemaStore = Schemas_1.SchemaStore.map((s) => s); } if (this._schemaCache.has(currentType.name)) { return Object.assign({}, this._schemaCache.get(currentType.name)); } const schema = this._schemaStore.find((s) => s.ContentTypeName === currentType.name); if (!schema) { return this.GetSchema(ContentTypes_1.GenericContent); } const parentSchema = schema.ParentTypeName && this._schemaStore.find((s) => s.ContentTypeName === schema.ParentTypeName); if (parentSchema) { schema.FieldSettings = [...schema.FieldSettings, ...parentSchema.FieldSettings]; } this._schemaCache.set(currentType.name, schema); return Object.assign({}, schema); } } exports.BaseRepository = BaseRepository; //# sourceMappingURL=BaseRepository.js.map |