diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/Utils.ts | 10 | ||||
-rw-r--r-- | src/client/Server.ts | 66 | ||||
-rw-r--r-- | src/client/SocketStub.ts | 15 | ||||
-rw-r--r-- | src/client/views/Main.tsx | 129 | ||||
-rw-r--r-- | src/fields/Document.ts | 46 | ||||
-rw-r--r-- | src/fields/KeyStore.ts | 2 | ||||
-rw-r--r-- | src/mobile/ImageUpload.tsx | 38 | ||||
-rw-r--r-- | src/server/RouteStore.ts | 5 | ||||
-rw-r--r-- | src/server/authentication/controllers/WorkspacesMenu.tsx | 19 | ||||
-rw-r--r-- | src/server/authentication/controllers/user_controller.ts | 3 | ||||
-rw-r--r-- | src/server/authentication/models/current_user_utils.ts | 46 | ||||
-rw-r--r-- | src/server/authentication/models/user_model.ts | 11 | ||||
-rw-r--r-- | src/server/index.ts | 33 |
13 files changed, 227 insertions, 196 deletions
diff --git a/src/Utils.ts b/src/Utils.ts index a4db94809..be97dc90b 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -41,8 +41,14 @@ export class Utils { socket.emit(message.Message, args); } - public static EmitCallback<T>(socket: Socket | SocketIOClient.Socket, message: Message<T>, args: T, fn: (args: any) => any) { - socket.emit(message.Message, args, fn); + public static EmitCallback<T>(socket: Socket | SocketIOClient.Socket, message: Message<T>, args: T): Promise<any>; + public static EmitCallback<T>(socket: Socket | SocketIOClient.Socket, message: Message<T>, args: T, fn: (args: any) => any): void; + public static EmitCallback<T>(socket: Socket | SocketIOClient.Socket, message: Message<T>, args: T, fn?: (args: any) => any): void | Promise<any> { + if (fn) { + socket.emit(message.Message, args, fn); + } else { + return new Promise<any>(res => socket.emit(message.Message, args, res)); + } } public static AddServerHandler<T>(socket: Socket, message: Message<T>, handler: (args: T) => any) { diff --git a/src/client/Server.ts b/src/client/Server.ts index 7d882c76d..6a47076fb 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -15,37 +15,45 @@ export class Server { // Retrieves the cached value of the field and sends a request to the server for the real value (if it's not cached). // Call this is from within a reaction and test whether the return value is FieldWaiting. - // 'hackTimeout' is here temporarily for simplicity when debugging things. - public static GetField(fieldid: FieldId, callback: (field: Opt<Field>) => void): Opt<Field> | FIELD_WAITING { - let cached = this.ClientFieldsCached.get(fieldid); - if (!cached) { - this.ClientFieldsCached.set(fieldid, FieldWaiting); - SocketStub.SEND_FIELD_REQUEST(fieldid, action((field: Field | undefined) => { - let cached = this.ClientFieldsCached.get(fieldid); - if (cached != FieldWaiting) - callback(cached); - else { - if (field) { - this.ClientFieldsCached.set(fieldid, field); - } else { - this.ClientFieldsCached.delete(fieldid) + public static GetField(fieldid: FieldId): Promise<Opt<Field>>; + public static GetField(fieldid: FieldId, callback: (field: Opt<Field>) => void): void; + public static GetField(fieldid: FieldId, callback?: (field: Opt<Field>) => void): Promise<Opt<Field>> | void { + let fn = (cb: (field: Opt<Field>) => void) => { + + let cached = this.ClientFieldsCached.get(fieldid); + if (!cached) { + this.ClientFieldsCached.set(fieldid, FieldWaiting); + SocketStub.SEND_FIELD_REQUEST(fieldid, action((field: Field | undefined) => { + let cached = this.ClientFieldsCached.get(fieldid); + if (cached != FieldWaiting) + cb(cached); + else { + if (field) { + this.ClientFieldsCached.set(fieldid, field); + } else { + this.ClientFieldsCached.delete(fieldid) + } + cb(field) } - callback(field) - } - })); - } else if (cached != FieldWaiting) { - setTimeout(() => callback(cached as Field), 0); + })); + } else if (cached != FieldWaiting) { + setTimeout(() => cb(cached as Field), 0); + } else { + reaction(() => { + return this.ClientFieldsCached.get(fieldid); + }, (field, reaction) => { + if (field !== "<Waiting>") { + reaction.dispose() + cb(field) + } + }) + } + } + if (callback) { + fn(callback); } else { - reaction(() => { - return this.ClientFieldsCached.get(fieldid); - }, (field, reaction) => { - if (field !== FieldWaiting) { - reaction.dispose() - callback(field) - } - }) + return new Promise<Opt<Field>>(res => fn(res)); } - return cached; } public static GetFields(fieldIds: FieldId[], callback: (fields: { [id: string]: Field }) => any) { @@ -71,7 +79,7 @@ export class Server { } } reaction(() => { - return waitingFieldIds.map(this.ClientFieldsCached.get); + return waitingFieldIds.map(id => this.ClientFieldsCached.get(id)); }, (cachedFields, reaction) => { if (!cachedFields.some(field => !field || field === FieldWaiting)) { reaction.dispose(); diff --git a/src/client/SocketStub.ts b/src/client/SocketStub.ts index a0b89b7c9..27528c4c3 100644 --- a/src/client/SocketStub.ts +++ b/src/client/SocketStub.ts @@ -35,16 +35,23 @@ export class SocketStub { Utils.Emit(Server.Socket, MessageStore.AddDocument, new DocumentTransfer(document.ToJson())) } - public static SEND_FIELD_REQUEST(fieldid: FieldId, callback: (field: Opt<Field>) => void) { - if (fieldid) { + public static SEND_FIELD_REQUEST(fieldid: FieldId): Promise<Opt<Field>>; + public static SEND_FIELD_REQUEST(fieldid: FieldId, callback: (field: Opt<Field>) => void): void; + public static SEND_FIELD_REQUEST(fieldid: FieldId, callback?: (field: Opt<Field>) => void): Promise<Opt<Field>> | void { + let fn = function (cb: (field: Opt<Field>) => void) { Utils.EmitCallback(Server.Socket, MessageStore.GetField, fieldid, (field: any) => { if (field) { - ServerUtils.FromJson(field).init(callback); + ServerUtils.FromJson(field).init(cb); } else { - callback(undefined); + cb(undefined); } }) } + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)) + } } public static SEND_FIELDS_REQUEST(fieldIds: FieldId[], callback: (fields: { [key: string]: Field }) => any) { diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 53a5aba6e..d2ba6998c 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -8,6 +8,7 @@ import "./Main.scss"; import { MessageStore } from '../../server/Message'; import { Utils } from '../../Utils'; import * as request from 'request' +import * as rp from 'request-promise' import { Documents } from '../documents/Documents'; import { Server } from '../Server'; import { setupDrag } from '../util/DragManager'; @@ -40,7 +41,7 @@ import Measure from 'react-measure'; import { DashUserModel } from '../../server/authentication/models/user_model'; import { ServerUtils } from '../../server/ServerUtil'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; -import { Field, Opt } from '../../fields/Field'; +import { Field, Opt, FieldWaiting } from '../../fields/Field'; import { ListField } from '../../fields/ListField'; import { Gateway, Settings } from '../northstar/manager/Gateway'; import { Catalog, Schema, Attribute, AttributeGroup } from '../northstar/model/idea/idea'; @@ -51,14 +52,27 @@ import '../northstar/utils/Extensions' @observer export class Main extends React.Component { // dummy initializations keep the compiler happy - @observable private mainContainer?: Document; @observable private mainfreeform?: Document; - @observable private userWorkspaces: Document[] = []; @observable public pwidth: number = 0; @observable public pheight: number = 0; @observable ActiveSchema: Schema | undefined; private _northstarColumns: Document[] = []; + @computed private get mainContainer(): Document | undefined { + let doc = this.userDocument.GetT(KeyStore.ActiveWorkspace, Document); + return doc == FieldWaiting ? undefined : doc; + } + + private set mainContainer(doc: Document | undefined) { + if (doc) { + this.userDocument.Set(KeyStore.ActiveWorkspace, doc); + } + } + + private get userDocument(): Document { + return CurrentUserUtils.UserDocument; + } + public mainDocId: string | undefined; private currentUser?: DashUserModel; public static Instance: Main; @@ -70,9 +84,12 @@ export class Main extends React.Component { configure({ enforceActions: "observed" }); if (window.location.pathname !== RouteStore.home) { let pathname = window.location.pathname.split("/"); - this.mainDocId = pathname[pathname.length - 1]; + if (pathname.length > 1 && pathname[pathname.length - 2] == 'doc') { + this.mainDocId = pathname[pathname.length - 1]; + } }; + // this.initializeNorthstar(); let y = ""; y.ReplaceAll("a", "B"); @@ -131,63 +148,50 @@ export class Main extends React.Component { initAuthenticationRouters = () => { // Load the user's active workspace, or create a new one if initial session after signup - request.get(ServerUtils.prepend(RouteStore.getActiveWorkspace), (error, response, body) => { - if (this.mainDocId || body) { - Server.GetField(this.mainDocId || body, field => { - if (field instanceof Document) { - this.openWorkspace(field); - this.populateWorkspaces(); - } else { - this.createNewWorkspace(true, this.mainDocId); - } - }); - } else { - this.createNewWorkspace(true, this.mainDocId); - } - }); - } - - @action - createNewWorkspace = (init: boolean, id?: string): void => { - let mainDoc = Documents.DockDocument(JSON.stringify({ content: [{ type: 'row', content: [] }] }), { title: `Main Container ${this.userWorkspaces.length + 1}` }, id); - let newId = mainDoc.Id; - request.post(ServerUtils.prepend(RouteStore.addWorkspace), { - body: { target: newId }, - json: true - }, () => { if (init) this.populateWorkspaces(); }); - - // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) - setTimeout(() => { - let freeformDoc = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" }); - var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] }; - mainDoc.SetText(KeyStore.Data, JSON.stringify(dockingLayout)); - mainDoc.Set(KeyStore.ActiveFrame, freeformDoc); - this.openWorkspace(mainDoc); - let pendingDocument = Documents.SchemaDocument([], { title: "New Mobile Uploads" }) - mainDoc.Set(KeyStore.OptionalRightCollection, pendingDocument); - }, 0); - this.userWorkspaces.push(mainDoc); + if (!this.mainDocId) { + this.userDocument.GetTAsync(KeyStore.ActiveWorkspace, Document).then(doc => { + if (doc) { + this.openWorkspace(doc); + } else { + this.createNewWorkspace(); + } + }) + } else { + Server.GetField(this.mainDocId).then(field => { + if (field instanceof Document) { + this.openWorkspace(field) + } else { + this.createNewWorkspace(this.mainDocId); + } + }) + } } @action - populateWorkspaces = () => { - // retrieve all workspace documents from the server - request.get(ServerUtils.prepend(RouteStore.getAllWorkspaces), (error, res, body) => { - let ids = JSON.parse(body) as string[]; - Server.GetFields(ids, action((fields: { [id: string]: Field }) => this.userWorkspaces = ids.map(id => fields[id] as Document))); - }); + createNewWorkspace = (id?: string): void => { + this.userDocument.GetTAsync<ListField<Document>>(KeyStore.Workspaces, ListField).then(action((list: Opt<ListField<Document>>) => { + if (list) { + let freeformDoc = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" }); + var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] }; + let mainDoc = Documents.DockDocument(JSON.stringify(dockingLayout), { title: `Main Container ${list.Data.length + 1}` }, id); + list.Data.push(mainDoc); + // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) + setTimeout(() => { + mainDoc.Set(KeyStore.ActiveFrame, freeformDoc); + this.openWorkspace(mainDoc); + let pendingDocument = Documents.SchemaDocument([], { title: "New Mobile Uploads" }) + mainDoc.Set(KeyStore.OptionalRightCollection, pendingDocument); + }, 0); + } + })); } @action openWorkspace = (doc: Document, fromHistory = false): void => { - request.post(ServerUtils.prepend(RouteStore.setActiveWorkspace), { - body: { target: doc.Id }, - json: true - }); this.mainContainer = doc; fromHistory || window.history.pushState(null, doc.Title, "/doc/" + doc.Id); this.mainContainer.GetTAsync(KeyStore.ActiveFrame, Document, field => this.mainfreeform = field); - this.mainContainer.GetTAsync(KeyStore.OptionalRightCollection, Document, col => { + this.userDocument.GetTAsync(KeyStore.OptionalRightCollection, Document).then(col => { // if there is a pending doc, and it has new data, show it (syip: we use a timeout to prevent collection docking view from being uninitialized) setTimeout(() => { if (col) { @@ -201,10 +205,15 @@ export class Main extends React.Component { }); } + @observable + workspacesShown: boolean = false; + + areWorkspacesShown = () => { + return this.workspacesShown; + } + @action toggleWorkspaces = () => { - if (WorkspacesMenu.Instance) { - WorkspacesMenu.Instance.toggle() - } + this.workspacesShown = !this.workspacesShown; } screenToLocalTransform = () => Transform.Identity @@ -300,6 +309,12 @@ export class Main extends React.Component { } render() { + let workspaceMenu: any = null; + let workspaces = this.userDocument.GetT<ListField<Document>>(KeyStore.Workspaces, ListField); + if (workspaces && workspaces !== FieldWaiting) { + workspaceMenu = <WorkspacesMenu active={this.mainContainer} open={this.openWorkspace} new={this.createNewWorkspace} allWorkspaces={workspaces.Data} + isShown={this.areWorkspacesShown} toggle={this.toggleWorkspaces} /> + } return ( <div id="main-div"> <Measure onResize={(r: any) => runInAction(() => { @@ -316,7 +331,7 @@ export class Main extends React.Component { <ContextMenu /> {this.nodesMenu} {this.miscButtons} - <WorkspacesMenu active={this.mainContainer} open={this.openWorkspace} new={this.createNewWorkspace} allWorkspaces={this.userWorkspaces} /> + {workspaceMenu} <InkingControl /> </div> ); @@ -360,4 +375,6 @@ export class Main extends React.Component { } } -ReactDOM.render(<Main />, document.getElementById('root')); +CurrentUserUtils.loadCurrentUser().then(() => { + ReactDOM.render(<Main />, document.getElementById('root')); +}); diff --git a/src/fields/Document.ts b/src/fields/Document.ts index 2403c670c..fc4906d17 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -124,22 +124,31 @@ export class Document extends Field { * Note: The callback will not be called if there is no associated field. * @returns `true` if the field exists on the document and `callback` will be called, and `false` otherwise */ - GetAsync(key: Key, callback: (field: Field) => void): boolean { + GetAsync(key: Key, callback: (field: Opt<Field>) => void): void { //TODO: This currently doesn't deal with prototypes let field = this.fields.get(key.Id); if (field && field.field) { callback(field.field); } else if (this._proxies.has(key.Id)) { Server.GetDocumentField(this, key, callback); - return true; + } else { + callback(undefined); } - return false; } - GetTAsync<T extends Field>(key: Key, ctor: { new(): T }, callback: (field: Opt<T>) => void): boolean { - return this.GetAsync(key, (field) => { - callback(Cast(field, ctor)); - }) + GetTAsync<T extends Field>(key: Key, ctor: { new(): T }): Promise<Opt<T>>; + GetTAsync<T extends Field>(key: Key, ctor: { new(): T }, callback: (field: Opt<T>) => void): void; + GetTAsync<T extends Field>(key: Key, ctor: { new(): T }, callback?: (field: Opt<T>) => void): Promise<Opt<T>> | void { + let fn = (cb: (field: Opt<T>) => void) => { + return this.GetAsync(key, (field) => { + cb(Cast(field, ctor)); + }); + } + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)); + } } /** @@ -215,13 +224,6 @@ export class Document extends Field { } @action - SetOnPrototype(key: Key, field: Field | undefined): void { - this.GetAsync(KeyStore.Prototype, (f: Field) => { - (f as Document).Set(key, field) - }) - } - - @action Set(key: Key, field: Field | undefined, setOnPrototype = false): void { let old = this.fields.get(key.Id); let oldField = old ? old.field : undefined; @@ -249,15 +251,21 @@ export class Document extends Field { } @action + SetOnPrototype(key: Key, field: Field | undefined): void { + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt<Document>) => { + f && f.Set(key, field) + }) + } + + @action SetDataOnPrototype<T, U extends Field & { Data: T }>(key: Key, value: T, ctor: { new(): U }, replaceWrongType = true) { - this.GetAsync(KeyStore.Prototype, (f: Field) => { - (f as Document).SetData(key, value, ctor) + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt<Document>) => { + f && f.SetData(key, value, ctor) }) } @action SetData<T, U extends Field & { Data: T }>(key: Key, value: T, ctor: { new(): U }, replaceWrongType = true) { - let field = this.Get(key, true); if (field instanceof ctor) { field.Data = value; @@ -294,8 +302,8 @@ export class Document extends Field { CreateAlias(id?: string): Document { let alias = new Document(id) - this.GetAsync(KeyStore.Prototype, (f: Field) => { - alias.Set(KeyStore.Prototype, f) + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt<Document>) => { + f && alias.Set(KeyStore.Prototype, f) }) return alias diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index 319702cc4..611e2951b 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -28,6 +28,7 @@ export namespace KeyStore { export const SchemaSplitPercentage = new Key("SchemaSplitPercentage"); export const Caption = new Key("Caption"); export const ActiveFrame = new Key("ActiveFrame"); + export const ActiveWorkspace = new Key("ActiveWorkspace"); export const ActiveDB = new Key("ActiveDB"); export const DocumentText = new Key("DocumentText"); export const LinkedToDocs = new Key("LinkedToDocs"); @@ -42,4 +43,5 @@ export namespace KeyStore { export const OptionalRightCollection = new Key("OptionalRightCollection"); export const Archives = new Key("Archives"); export const Updated = new Key("Updated"); + export const Workspaces = new Key("Workspaces"); } diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index 16808a598..47b9d8f0b 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -7,7 +7,7 @@ import { Server } from '../client/Server'; import { Documents } from '../client/documents/Documents'; import { ListField } from '../fields/ListField'; import { ImageField } from '../fields/ImageField'; -import request = require('request'); +import * as rp from 'request-promise' import { ServerUtils } from '../server/ServerUtil'; import { RouteStore } from '../server/RouteStore'; @@ -40,28 +40,24 @@ const onFileLoad = (file: any) => { json.map((file: any) => { let path = window.location.origin + file var doc: Document = Documents.ImageDocument(path, { nativeWidth: 200, width: 200 }) - doc.GetTAsync(KeyStore.Data, ImageField, (i) => { - if (i) { - document.getElementById("message")!.innerText = i.Data.href; + + rp.get(ServerUtils.prepend(RouteStore.getUserDocumentId)).then(res => { + if (res) { + return Server.GetField(res); + } + throw new Error("No user id returned"); + }).then(field => { + if (field instanceof Document) { + return field.GetTAsync(KeyStore.OptionalRightCollection, Document) } - }) - request.get(ServerUtils.prepend(RouteStore.getActiveWorkspace), (error, response, body) => { - if (body) { - Server.GetField(body, field => { - if (field instanceof Document) { - field.GetTAsync(KeyStore.OptionalRightCollection, Document, - pending => { - if (pending) { - pending.GetOrCreateAsync(KeyStore.Data, ListField, list => { - list.Data.push(doc); - }) - } - }) - } - } - ); + }).then(pending => { + if (pending) { + pending.GetOrCreateAsync(KeyStore.Data, ListField, list => { + list.Data.push(doc); + }) } - }) + }); + // console.log(window.location.origin + file[0]) //imgPrev.setAttribute("src", window.location.origin + files[0].name) diff --git a/src/server/RouteStore.ts b/src/server/RouteStore.ts index fb06b878b..fdf5b6a5c 100644 --- a/src/server/RouteStore.ts +++ b/src/server/RouteStore.ts @@ -15,10 +15,7 @@ export enum RouteStore { // USER AND WORKSPACES getCurrUser = "/getCurrentUser", - addWorkspace = "/addWorkspaceId", - getAllWorkspaces = "/getAllWorkspaceIds", - getActiveWorkspace = "/getActiveWorkspaceId", - setActiveWorkspace = "/setActiveWorkspaceId", + getUserDocumentId = "/getUserDocumentId", updateCursor = "/updateCursor", openDocumentWithId = "/doc/:docId", diff --git a/src/server/authentication/controllers/WorkspacesMenu.tsx b/src/server/authentication/controllers/WorkspacesMenu.tsx index 1533b1e62..8e14cf98e 100644 --- a/src/server/authentication/controllers/WorkspacesMenu.tsx +++ b/src/server/authentication/controllers/WorkspacesMenu.tsx @@ -9,30 +9,23 @@ import { KeyStore } from '../../../fields/KeyStore'; export interface WorkspaceMenuProps { active: Document | undefined; open: (workspace: Document) => void; - new: (init: boolean) => void; + new: () => void; allWorkspaces: Document[]; + isShown: () => boolean; + toggle: () => void; } @observer export class WorkspacesMenu extends React.Component<WorkspaceMenuProps> { - static Instance: WorkspacesMenu; - @observable private workspacesExposed: boolean = false; - constructor(props: WorkspaceMenuProps) { super(props); - WorkspacesMenu.Instance = this; this.addNewWorkspace = this.addNewWorkspace.bind(this); } @action addNewWorkspace() { - this.props.new(false); - this.toggle(); - } - - @action - toggle() { - this.workspacesExposed = !this.workspacesExposed; + this.props.new(); + this.props.toggle(); } render() { @@ -45,7 +38,7 @@ export class WorkspacesMenu extends React.Component<WorkspaceMenuProps> { borderRadius: 5, position: "absolute", top: 78, - left: this.workspacesExposed ? 11 : -500, + left: this.props.isShown() ? 11 : -500, background: "white", border: "black solid 2px", transition: "all 1s ease", diff --git a/src/server/authentication/controllers/user_controller.ts b/src/server/authentication/controllers/user_controller.ts index 2cef958e8..e365b8dce 100644 --- a/src/server/authentication/controllers/user_controller.ts +++ b/src/server/authentication/controllers/user_controller.ts @@ -11,6 +11,7 @@ import * as async from 'async'; import * as nodemailer from 'nodemailer'; import c = require("crypto"); import { RouteStore } from "../../RouteStore"; +import { Utils } from "../../../Utils"; /** * GET /signup @@ -54,7 +55,7 @@ export let postSignup = (req: Request, res: Response, next: NextFunction) => { const user = new User({ email, password, - userDoc: "document here" + userDocumentId: Utils.GenerateGuid() }); User.findOne({ email }, (err, existingUser) => { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index cc433eb73..17a6d493b 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -1,29 +1,61 @@ import { DashUserModel } from "./user_model"; -import * as request from 'request' +import * as rp from 'request-promise'; import { RouteStore } from "../../RouteStore"; import { ServerUtils } from "../../ServerUtil"; +import { Server } from "../../../client/Server"; +import { Document } from "../../../fields/Document"; +import { KeyStore } from "../../../fields/KeyStore"; +import { ListField } from "../../../fields/ListField"; +import { Documents } from "../../../client/documents/Documents"; export class CurrentUserUtils { private static curr_email: string; private static curr_id: string; + private static user_document: Document; - public static get email() { + public static get email(): string { return CurrentUserUtils.curr_email; } - public static get id() { + public static get id(): string { return CurrentUserUtils.curr_id; } - public static loadCurrentUser() { - request.get(ServerUtils.prepend(RouteStore.getCurrUser), (error, response, body) => { - if (body) { - let obj = JSON.parse(body); + public static get UserDocument(): Document { + return CurrentUserUtils.user_document; + } + + private static createUserDocument(id: string): Document { + let doc = new Document(id); + + doc.Set(KeyStore.Workspaces, new ListField<Document>()); + doc.Set(KeyStore.OptionalRightCollection, Documents.SchemaDocument([], { title: "Pending documents" })) + return doc; + } + + public static loadCurrentUser(): Promise<any> { + let userPromise = rp.get(ServerUtils.prepend(RouteStore.getCurrUser)).then((response) => { + if (response) { + let obj = JSON.parse(response); CurrentUserUtils.curr_id = obj.id as string; CurrentUserUtils.curr_email = obj.email as string; } else { throw new Error("There should be a user! Why does Dash think there isn't one?") } }); + let userDocPromise = rp.get(ServerUtils.prepend(RouteStore.getUserDocumentId)).then(id => { + if (id) { + return Server.GetField(id).then(field => { + if (field instanceof Document) { + this.user_document = field; + } else { + this.user_document = this.createUserDocument(id); + } + }) + } else { + throw new Error("There should be a user id! Why does Dash think there isn't one?") + } + }); + return Promise.all([userPromise, userDocPromise]); } }
\ No newline at end of file diff --git a/src/server/authentication/models/user_model.ts b/src/server/authentication/models/user_model.ts index 3d4ed6896..81580aad5 100644 --- a/src/server/authentication/models/user_model.ts +++ b/src/server/authentication/models/user_model.ts @@ -21,9 +21,7 @@ export type DashUserModel = mongoose.Document & { passwordResetToken: string | undefined, passwordResetExpires: Date | undefined, - allWorkspaceIds: Array<String>, - activeWorkspaceId: String, - activeUsersId: String, + userDocumentId: string; profile: { name: string, @@ -49,12 +47,7 @@ const userSchema = new mongoose.Schema({ passwordResetToken: String, passwordResetExpires: Date, - allWorkspaceIds: { - type: Array, - default: [] - }, - activeWorkspaceId: String, - activeUsersId: String, + userDocumentId: String, facebook: String, twitter: String, diff --git a/src/server/index.ts b/src/server/index.ts index d1eb6847d..16304f1c5 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -156,16 +156,9 @@ addSecureRoute( addSecureRoute( Method.GET, - (user, res) => res.send(user.activeWorkspaceId || ""), + (user, res) => res.send(user.userDocumentId || ""), undefined, - RouteStore.getActiveWorkspace, -); - -addSecureRoute( - Method.GET, - (user, res) => res.send(JSON.stringify(user.allWorkspaceIds)), - undefined, - RouteStore.getAllWorkspaces + RouteStore.getUserDocumentId, ); addSecureRoute( @@ -185,28 +178,6 @@ addSecureRoute( addSecureRoute( Method.POST, (user, res, req) => { - user.update({ $set: { activeWorkspaceId: req.body.target } }, (err, raw) => { - res.sendStatus(err ? 500 : 200); - }); - }, - undefined, - RouteStore.setActiveWorkspace -); - -addSecureRoute( - Method.POST, - (user, res, req) => { - user.update({ $push: { allWorkspaceIds: req.body.target } }, (err, raw) => { - res.sendStatus(err ? 500 : 200); - }); - }, - undefined, - RouteStore.addWorkspace -); - -addSecureRoute( - Method.POST, - (user, res, req) => { let form = new formidable.IncomingForm() form.uploadDir = __dirname + "/public/files/" form.keepExtensions = true |