Commit 8dfc9b3a authored by Mark Harding's avatar Mark Harding

(chore): performance bumps and browser specific delays

1 merge request!343WIP: Epic/ssr
Pipeline #108414697 failed with stages
in 3 minutes and 35 seconds
......@@ -5990,8 +5990,7 @@
"clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=",
"dev": true
"integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18="
},
"clone-buffer": {
"version": "1.0.0",
......@@ -15376,6 +15375,14 @@
"integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==",
"dev": true
},
"node-cache": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.0.tgz",
"integrity": "sha512-gFQwYdoOztBuPlwg6DKQEf50G+gkK69aqLnw4djkmlHCzeVrLJfwvg9xl4RCAGviTIMUVoqcyoZ/V/wPEu/VVg==",
"requires": {
"clone": "2.x"
}
},
"node-fetch-npm": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/node-fetch-npm/-/node-fetch-npm-2.0.2.tgz",
......
......@@ -57,6 +57,7 @@
"medium-editor": "^5.23.2",
"ngx-drag-drop": "^2.0.0",
"ngx-plyr": "^3.0.1",
"node-cache": "^5.1.0",
"plotly.js": "^1.47.4",
"plyr": "^3.5.6",
"qrcodejs2": "0.0.2",
......
......@@ -7,25 +7,19 @@ import { readFileSync } from 'fs';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
import { enableProdMode } from '@angular/core';
import { XhrFactory } from '@angular/common/http';
import { NgxRequest, NgxResponce } from '@gorniv/ngx-universal';
import * as express from 'express';
import * as proxy from 'express-http-proxy';
import * as compression from 'compression';
import * as cookieparser from 'cookie-parser';
import { NgxRequest, NgxResponce } from '@gorniv/ngx-universal';
import * as xhr2 from 'xhr2';
const domino = require('domino');
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// activate cookie for server-side rendering
xhr2.prototype._restrictedHeaders.cookie = false;
xhr2.prototype._restrictedHeaders.cookie2 = false;
// xhr2.prototype._privateHeaders = {};
// Express server
const app = express();
......@@ -42,6 +36,7 @@ const win = domino.createWindow(template);
global['window'] = win;
global['Node'] = win.Node;
global['navigator'] = win.navigator;
global['screen'] = { width: 0, height: 0 };
global['Event'] = win.Event;
global['Event']['prototype'] = win.Event.prototype;
global['document'] = win.document;
......@@ -76,7 +71,6 @@ global['window']['Minds'] = {
'top-feeds-by-age': true,
},
};
global['XMLHttpRequest'] = xhr2; // Needed?
global['window']['localStorage'] = {
getItem: () => null,
setItem: () => {},
......@@ -124,8 +118,43 @@ app.set('views', DIST_FOLDER);
// Server static files from dist folder
app.get('*.*', express.static(DIST_FOLDER));
// Socket.io hitting wrong endpoint (dev?)
app.get('/socket.io', (req, res) => {
res.send('You are using the wrong domain.');
});
// /undefined is an issue with angular
app.get('/undefined', (req, res) => {
res.send('There was problem');
});
// cache
const NodeCache = require('node-cache');
const myCache = new NodeCache({ stdTTL: 5 * 60, checkperiod: 120 });
const cache = () => {
return (req, res, next) => {
const sessKey = req.cookies['minds_sess'] || 'loggedout';
const key = `__express__/${sessKey}/` + (req.originalUrl || req.url);
const exists = myCache.has(key);
if (exists) {
console.log(`from cache: ${key}`);
const cachedBody = myCache.get(key);
res.send(cachedBody);
return;
} else {
res.sendResponse = res.send;
res.send = body => {
myCache.set(key, body);
res.sendResponse(body);
};
next();
}
};
};
// All regular routes use the Universal engine
app.get('*', (req, res) => {
app.get('*', cache(), (req, res) => {
const http =
req.headers['x-forwarded-proto'] === undefined
? 'http'
......
<ng-container *ngIf="ready">
<ng-container *ngIf="!isProDomain">
<m-v2-topbar *mIfFeature="'top-feeds'; else legacyTopbar">
<m-v2-topbar>
<ng-container search>
<m-search--bar [defaultSizes]="false"></m-search--bar>
</ng-container>
......@@ -11,18 +11,6 @@
></m-notifications--topbar-toggle>
</ng-container>
</m-v2-topbar>
<ng-template #legacyTopbar>
<m-topbar class="m-noshadow">
<ng-container search>
<m-search--bar></m-search--bar>
</ng-container>
<ng-container icons>
<m-notifications--topbar-toggle></m-notifications--topbar-toggle>
<m-wallet--topbar-toggle></m-wallet--topbar-toggle>
</ng-container>
</m-topbar>
</ng-template>
<m-sidebar--markers
[class.has-v2-navbar]="featuresService.has('top-feeds')"
......@@ -30,6 +18,7 @@
</ng-container>
<m-body
[class.has-markers-sidebar]="session.isLoggedIn()"
[class.has-v2-navbar]="featuresService.has('top-feeds')"
[class.is-pro-domain]="isProDomain"
>
......
......@@ -2,11 +2,21 @@ import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { ServerTransferStateModule } from '@angular/platform-server';
import { XhrFactory } from '@angular/common/http';
import * as xhr2 from 'xhr2';
import { MindsModule } from './app.module';
import { Minds } from './app.component';
import { PlotlyModule } from 'angular-plotly.js';
// activate cookie for server-side rendering
export class ServerXhr implements XhrFactory {
build(): XMLHttpRequest {
xhr2.prototype._restrictedHeaders.cookie = false;
return new xhr2.XMLHttpRequest();
}
}
@NgModule({
imports: [
MindsModule,
......@@ -15,6 +25,7 @@ import { PlotlyModule } from 'angular-plotly.js';
ServerTransferStateModule,
PlotlyModule,
],
providers: [{ provide: XhrFactory, useClass: ServerXhr }],
bootstrap: [Minds],
})
export class AppServerModule {}
......@@ -9,11 +9,14 @@ import {
OnInit,
SkipSelf,
ViewChild,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { FeaturedContentService } from './featured-content.service';
import { DynamicHostDirective } from '../../directives/dynamic-host.directive';
import { Activity } from '../../../modules/legacy/components/cards/activity/activity';
import { ClientMetaService } from '../../services/client-meta.service';
import { isPlatformBrowser } from '@angular/common';
@Component({
selector: 'm-featured-content',
......@@ -34,13 +37,14 @@ export class FeaturedContentComponent implements OnInit {
protected componentFactoryResolver: ComponentFactoryResolver,
protected cd: ChangeDetectorRef,
protected clientMetaService: ClientMetaService,
@SkipSelf() protected injector: Injector
@SkipSelf() protected injector: Injector,
@Inject(PLATFORM_ID) private platformId
) {
this.clientMetaService.inherit(injector).setMedium('featured-content');
}
ngOnInit() {
this.load();
if (isPlatformBrowser(this.platformId)) this.load();
}
async load() {
......
......@@ -10,10 +10,9 @@ import {
import { isPlatformBrowser } from '@angular/common';
@Directive({
selector: '[mIfBrowser]'
selector: '[mIfBrowser]',
})
export class IfBrowserDirective {
private _elseTemplateRef: TemplateRef<any>;
private _viewRef: EmbeddedViewRef<any>;
private _elseViewRef: EmbeddedViewRef<any>;
......@@ -21,21 +20,21 @@ export class IfBrowserDirective {
constructor(
private _templateRef: TemplateRef<any>,
private _viewContainerRef: ViewContainerRef,
@Inject(PLATFORM_ID) private platformId,
@Inject(PLATFORM_ID) private platformId
) {
console.log('constructing IfBrowserDirective');
this._update();
}
_update() {
console.log(this.platformId, isPlatformBrowser);
if (isPlatformBrowser(this.platformId)) {
if (!this._viewRef) {
this._viewContainerRef.clear();
this._elseViewRef = void 0;
if (this._templateRef) {
this._viewRef = this._viewContainerRef.createEmbeddedView(this._templateRef);
this._viewRef = this._viewContainerRef.createEmbeddedView(
this._templateRef
);
}
}
} else {
......@@ -44,7 +43,9 @@ export class IfBrowserDirective {
this._viewRef = void 0;
if (this._elseTemplateRef) {
this._elseViewRef = this._viewContainerRef.createEmbeddedView(this._elseTemplateRef);
this._elseViewRef = this._viewContainerRef.createEmbeddedView(
this._elseTemplateRef
);
}
}
}
......
......@@ -47,13 +47,9 @@ export class SidebarMarkersComponent {
return;
}
const mBody: any = document.getElementsByTagName('m-body')[0];
if (showMarkerSidebar) {
mBody.classList.add('has-markers-sidebar');
this.createGroupsSideBar();
} else {
mBody.classList.remove('has-markers-sidebar');
this.host.viewContainerRef.clear();
}
this.showMarkerSidebar = showMarkerSidebar;
......
import { Injectable, Injector } from '@angular/core';
import { Location } from '@angular/common';
import { Injectable, Injector, Inject, PLATFORM_ID } from '@angular/core';
import { Location, isPlatformServer } from '@angular/common';
import hashCode from '../../helpers/hash-code';
import { Session } from '../../services/session';
import { Client } from '../../services/api';
......@@ -27,7 +27,8 @@ export class ClientMetaService {
constructor(
protected location: Location,
protected session: Session,
protected client: Client
protected client: Client,
@Inject(PLATFORM_ID) private platformId
) {
this.id = ++uniqId;
......@@ -152,6 +153,7 @@ export class ClientMetaService {
}
async recordView(entity) {
if (isPlatformServer(this.platformId)) return; // Browser will record too.
await this.client.post('api/v2/analytics/views/entity/' + entity.guid, {
client_meta: this.build(),
});
......
......@@ -12,13 +12,12 @@ export class ConfigsService {
async loadFromRemote() {
try {
this.configs = await this.client.get('api/v1/minds/config');
console.log(this.configs);
} catch (err) {
console.error(err);
}
}
get(key) {
return this.configs[key] || {};
return this.configs[key] || null;
}
}
import { Component, OnDestroy, OnInit } from '@angular/core';
import {
Component,
OnDestroy,
OnInit,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { Client } from '../../services/api';
import { Session } from '../../services/session';
import { Storage } from '../../services/storage';
import { Subscription } from 'rxjs';
import { SettingsService } from '../settings/settings.service';
import { isPlatformServer } from '@angular/common';
@Component({
selector: 'm-ads-boost',
......@@ -34,7 +41,8 @@ export class BoostAds implements OnInit, OnDestroy {
public client: Client,
public session: Session,
private storage: Storage,
private settingsService: SettingsService
private settingsService: SettingsService,
@Inject(PLATFORM_ID) private platformId
) {}
ngOnInit() {
......@@ -52,6 +60,7 @@ export class BoostAds implements OnInit, OnDestroy {
}
fetch() {
if (isPlatformServer(this.platformId)) return;
if (this.storage.get('boost:offset:sidebar'))
this.offset = this.storage.get('boost:offset:sidebar');
this.client
......
......@@ -5,7 +5,7 @@
else isProChannel
"
>
<m-channel #channelComponent></m-channel>
<m-channel [user]="channel" #channelComponent></m-channel>
</ng-container>
<ng-template #isProChannel>
<m-pro--channel #proChannelComponent></m-pro--channel>
......
import { Component, ViewChild, SkipSelf, Injector } from '@angular/core';
import { Component, ViewChild, SkipSelf, Injector, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';
......@@ -31,7 +31,7 @@ export class ChannelComponent {
isLocked: boolean = false;
username: string;
user: MindsUser;
@Input() user: MindsUser;
offset: string = '';
moreData: boolean = true;
inProgress: boolean = false;
......@@ -77,7 +77,7 @@ export class ChannelComponent {
this.editing = false;
if (params['username']) {
this.changed = this.username !== params['username'];
this.changed = this.user.username !== params['username'];
this.username = params['username'];
feedChanged = true;
......@@ -99,6 +99,7 @@ export class ChannelComponent {
if (this.changed) {
this.load();
console.log('reloading channel...');
} else if (feedChanged) {
console.log('reload feed with new settings');
}
......
......@@ -304,6 +304,7 @@
<div class="minds-spacer-2x"></div>
<m-wire-channel
*mIfBrowser
#wire
[(rewards)]="user.wire_rewards"
[channel]="user"
......
import { Component, EventEmitter, Output, ViewChild } from '@angular/core';
import {
Component,
EventEmitter,
Output,
ViewChild,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { Client, Upload } from '../../../services/api';
import { Session } from '../../../services/session';
import { MindsUser } from '../../../interfaces/entities';
......@@ -8,6 +15,7 @@ import { Storage } from '../../../services/storage';
import { OverlayModalService } from '../../../services/ux/overlay-modal';
import { ReferralsLinksComponent } from '../../wallet/tokens/referrals/links/links.component';
import { FeaturesService } from '../../../services/features.service';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
@Component({
moduleId: module.id,
......@@ -39,7 +47,8 @@ export class ChannelSidebar {
public onboardingService: ChannelOnboardingService,
protected storage: Storage,
private overlayModal: OverlayModalService,
public featuresService: FeaturesService
public featuresService: FeaturesService,
@Inject(PLATFORM_ID) private platformId
) {
if (onboardingService && onboardingService.onClose) {
onboardingService.onClose.subscribe(progress => {
......@@ -54,6 +63,7 @@ export class ChannelSidebar {
}
checkProgress() {
if (isPlatformServer(this.platformId)) return;
this.onboardingService.checkProgress().then(() => {
this.onboardingProgress = this.onboardingService.completedPercentage;
});
......@@ -65,6 +75,7 @@ export class ChannelSidebar {
shouldShowOnboardingProgress() {
return (
isPlatformBrowser(this.platformId) &&
this.session.isLoggedIn() &&
this.session.getLoggedInUser().guid === this.user.guid &&
!this.storage.get('onboarding_hide') &&
......
......@@ -4,6 +4,8 @@ import {
ViewChild,
ChangeDetectorRef,
HostListener,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { interval, timer } from 'rxjs';
import { startWith, map, tap, throttle } from 'rxjs/operators';
......@@ -11,6 +13,7 @@ import { startWith, map, tap, throttle } from 'rxjs/operators';
import { UpdateMarkersService } from '../../../common/services/update-markers.service';
import { Client } from '../../../services/api';
import { Session } from '../../../services/session';
import { isPlatformBrowser } from '@angular/common';
@Component({
selector: 'm-group--sidebar-markers',
......@@ -31,13 +34,16 @@ export class GroupsSidebarMarkersComponent {
private client: Client,
public session: Session,
private updateMarkers: UpdateMarkersService,
private cd: ChangeDetectorRef
private cd: ChangeDetectorRef,
@Inject(PLATFORM_ID) private platformId
) {}
async ngOnInit() {
this.onResize();
await this.load(true);
this.listenForMarkers();
if (isPlatformBrowser(this.platformId)) {
await this.load(true);
this.listenForMarkers();
}
}
listenForMarkers() {
......
......@@ -32,7 +32,11 @@
<b i18n="@@TAGS_SELECTOR__SELECT_UP_TO_5_HASHTAGS"
>Select up to 5 hashtags.</b
>
<m-form-tags-input [tags]="tags" (tagsChange)="setTags($event)">
<m-form-tags-input
*mIfBrowser
[tags]="tags"
(tagsChange)="setTags($event)"
>
</m-form-tags-input>
</li>
</ul>
......
......@@ -6,11 +6,14 @@ import {
Input,
OnInit,
Output,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { TopbarHashtagsService } from '../service/topbar.service';
import { Tag } from '../types/tag';
import { findLastIndex } from '../../../utils/array-utils';
import { Storage } from '../../../services/storage';
import { isPlatformServer } from '@angular/common';
export type SideBarSelectorChange = { type: string; value?: any };
......@@ -40,7 +43,8 @@ export class SidebarSelectorComponent implements OnInit {
constructor(
protected topbarHashtagsService: TopbarHashtagsService,
protected changeDetectorRef: ChangeDetectorRef,
protected storage: Storage
protected storage: Storage,
@Inject(PLATFORM_ID) private platformId
) {}
ngOnInit() {
......@@ -61,6 +65,8 @@ export class SidebarSelectorComponent implements OnInit {
this.loading = true;
this.detectChanges();
if (isPlatformServer(this.platformId)) return; // Don't load server side, do async
try {
this.hashtags = await this.topbarHashtagsService.loadAll({
softLimit: 25,
......
......@@ -126,6 +126,7 @@
</div>
<m-translate
*mIfBrowser
[open]="translateToggle"
[entity]="activity"
[translateEvent]="translateEvent"
......@@ -432,12 +433,14 @@
</div>
</div>
<m-comments__tree
*ngIf="commentsToggle"
[entity]="activity"
[canDelete]="canDelete"
>
</m-comments__tree>
<ng-container *mIfBrowser>
<m-comments__tree
*ngIf="commentsToggle"
[entity]="activity"
[canDelete]="canDelete"
>
</m-comments__tree>
</ng-container>
<div
class="m-activity--boost-notice mdl-card__supporting-text mdl-color--blue-grey-50"
......
......@@ -86,7 +86,6 @@ export class CarouselComponent {
* If the parent set edit mode
*/
set _editMode(value: boolean) {
console.log('[carousel]: edit mode event received');
//was in edit more, now settings not in edit more
if (this.editing && !value) {
console.log('[carousel]: edit mode ended');
......
......@@ -7,12 +7,15 @@ import {
Output,
EventEmitter,
ChangeDetectorRef,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { PLAYER_ANIMATIONS } from './player.animations';
import { VideoPlayerService, VideoSource } from './player.service';
import isMobile from '../../../../helpers/is-mobile';
import Plyr from 'plyr';
import { PlyrComponent } from 'ngx-plyr';
import { isPlatformBrowser } from '@angular/common';
@Component({
selector: 'm-videoPlayer',
......@@ -57,14 +60,17 @@ export class MindsVideoPlayerComponent implements OnInit, OnDestroy {
constructor(
private service: VideoPlayerService,
private cd: ChangeDetectorRef
private cd: ChangeDetectorRef,
@Inject(PLATFORM_ID) private platformId
) {}
ngOnInit(): void {
this.service.load().then(() => {
this.cd.markForCheck();
this.cd.detectChanges();
});
if (isPlatformBrowser(this.platformId)) {
this.service.load().then(() => {
this.cd.markForCheck();
this.cd.detectChanges();
});
}
}
ngOnDestroy(): void {}
......@@ -110,7 +116,7 @@ export class MindsVideoPlayerComponent implements OnInit, OnDestroy {
* @return boolean
*/
isPlayable(): boolean {
return this.service.isPlayable();
return isPlatformBrowser(this.platformId) && this.service.isPlayable();
}
/**
......
......@@ -5,6 +5,8 @@ import {
OnInit,
SkipSelf,
ViewChild,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { take, map, mergeMap } from 'rxjs/operators';
......@@ -26,6 +28,7 @@ import { NewsfeedHashtagSelectorService } from '../services/newsfeed-hashtag-sel
import { FeedsService } from '../../../common/services/feeds.service';
import { FeaturesService } from '../../../services/features.service';
import { ClientMetaService } from '../../../common/services/client-meta.service';
import { isPlatformServer } from '@angular/common';
@Component({
selector: 'm-newsfeed--sorted',
......@@ -75,7 +78,8 @@ export class NewsfeedSortedComponent implements OnInit, OnDestroy {
public feedsService: FeedsService,
protected featuresService: FeaturesService,
protected clientMetaService: ClientMetaService,
@SkipSelf() injector: Injector
@SkipSelf() injector: Injector,
@Inject(PLATFORM_ID) private platformId
) {
this.title.setTitle('Newsfeed');
......@@ -209,6 +213,7 @@ export class NewsfeedSortedComponent implements OnInit, OnDestroy {
refresh: boolean = false,
forceSync: boolean = false
) {
if (isPlatformServer(this.platformId)) return; // Logged in newsfeed for browser only
if (refresh) {
this.feedsService.clear();
}
......
......@@ -24,10 +24,12 @@
[attr.minds-data-activity-guid]="preActivity.guid"
></minds-activity>
<m-newsfeed--boost-rotator
interval="3"
*ngIf="showBoostRotator"
></m-newsfeed--boost-rotator>
<ng-container *mIfBrowser>
<m-newsfeed--boost-rotator
interval="3"
*ngIf="showBoostRotator"
></m-newsfeed--boost-rotator>
</ng-container>
<ng-container
*ngFor="let activity$ of feedsService.feed | async; let i = index"
......
import { Component, Injector, SkipSelf, ViewChild } from '@angular/core';
import {
Component,
Injector,
SkipSelf,
ViewChild,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { Subscription, BehaviorSubject } from 'rxjs';
import { filter } from 'rxjs/operators';
......@@ -22,6 +29,7 @@ import { FeaturesService } from '../../../services/features.service';
import { FeedsService } from '../../../common/services/feeds.service';
import { NewsfeedService } from '../services/newsfeed.service';
import { ClientMetaService } from '../../../common/services/client-meta.service';
import { isPlatformServer } from '@angular/common';
@Component({
selector: 'm-newsfeed--subscribed',
......@@ -70,7 +78,8 @@ export class NewsfeedSubscribedComponent {
public feedsService: FeedsService,
protected newsfeedService: NewsfeedService,
protected clientMetaService: ClientMetaService,
@SkipSelf() injector: Injector
@SkipSelf() injector: Injector,
@Inject(PLATFORM_ID) private platformId
) {
this.title.setTitle('Newsfeed');
......@@ -118,6 +127,7 @@ export class NewsfeedSubscribedComponent {
}
load(refresh: boolean = false, forceSync: boolean = false) {
if (isPlatformServer(this.platformId)) return;
if (this.featuresService.has('es-feeds')) {
this.loadFromService(refresh, forceSync);
} else {
......
import { NgModule } from '@angular/core';
import { NgModule, PLATFORM_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { CommonModule as NgCommonModule } from '@angular/common';
......@@ -23,10 +23,10 @@ import { NoticesService } from './notices.service';
providers: [
{
provide: NoticesService,
useFactory: _http => {
return new NoticesService(_http);
useFactory: (_http, platformId) => {
return new NoticesService(_http, platformId);
},
deps: [HttpClient],
deps: [HttpClient, PLATFORM_ID],
},
],
})
......
import { Injectable } from '@angular/core';
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { isPlatformServer } from '@angular/common';
const NOTICES_JSON_URL = 'https://cdn-assets.minds.com/notices.json';
......@@ -7,9 +8,13 @@ const NOTICES_JSON_URL = 'https://cdn-assets.minds.com/notices.json';
export class NoticesService {
notices: any[] = [];
constructor(protected client: HttpClient) {}
constructor(
protected client: HttpClient,
@Inject(PLATFORM_ID) private platformId
) {}
async getNotices() {
if (isPlatformServer(this.platformId)) return; // Do not fetch on server side
if (this.notices.length) return this.notices;
const timestamp = Date.now();
this.notices = (<{ notices }>(
......
......@@ -116,12 +116,12 @@ export class NotificationService {
* Sync Notifications to the topbar Counter
*/
sync() {
for (var i in window.Minds.navigation.topbar) {
if (window.Minds.navigation.topbar[i].name === 'Notifications') {
window.Minds.navigation.topbar[i].extras.counter =
window.Minds.notifications_count;
}
}
// for (var i in window.Minds.navigation.topbar) {
// if (window.Minds.navigation.topbar[i].name === 'Notifications') {
// window.Minds.navigation.topbar[i].extras.counter =
// window.Minds.notifications_count;
// }
// }
this.title.setCounter(window.Minds.notifications_count);
}
......
import { Inject, Injectable } from '@angular/core';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { Client } from './api/client';
import { SiteService } from '../common/services/site.service';
import { isPlatformServer } from '@angular/common';
@Injectable()
export class AnalyticsService {
private defaultPrevented: boolean = false;
static _(router: Router, client: Client, site: SiteService) {
return new AnalyticsService(router, client, site);
static _(router: Router, client: Client, site: SiteService, platformId) {
return new AnalyticsService(router, client, site, platformId);
}
constructor(
@Inject(Router) public router: Router,
@Inject(Client) public client: Client,
@Inject(SiteService) public site: SiteService
@Inject(SiteService) public site: SiteService,
@Inject(PLATFORM_ID) private platformId
) {
this.onRouterInit();
......@@ -30,6 +32,7 @@ export class AnalyticsService {
}
async send(type: string, fields: any = {}, entityGuid: string = null) {
if (isPlatformServer(this.platformId)) return; // Client side does these. Don't call twice
if (type === 'pageview') {
this.client.post('api/v2/mwa/pv', fields);
} else {
......
......@@ -74,10 +74,6 @@ export class Client {
getRaw(endpoint: string, data: Object = {}, options: Object = {}) {
endpoint += '?' + this.buildParams(data);
const STATE_KEY = makeStateKey(
`http-${endpoint}` + JSON.stringify(options)
);
return new Promise((resolve, reject) => {
this.http
.get(this.base + endpoint, this.buildOptions(options, true))
......@@ -86,10 +82,6 @@ export class Client {
var data: any = res;
if (!data || data.status !== 'success') return reject(data);
if (isPlatformServer(this.platformId)) {
const dump = JSON.stringify(data);
if (dump.length < 10000) this.transferState.set(STATE_KEY, dump);
}
return resolve(data);
},
err => {
......@@ -110,6 +102,7 @@ export class Client {
* Return a POST request
*/
post(endpoint: string, data: Object = {}, options: Object = {}) {
console.log(`POST: ${endpoint}`);
return new Promise((resolve, reject) => {
this.http
.post(
......@@ -182,6 +175,7 @@ export class Client {
* Return a PUT request
*/
put(endpoint: string, data: Object = {}, options: Object = {}) {
console.log(`PUT: ${endpoint}`);
return new Promise((resolve, reject) => {
this.http
.put(
......@@ -217,6 +211,7 @@ export class Client {
* Return a DELETE request
*/
delete(endpoint: string, data: Object = {}, options: Object = {}) {
console.log(`DELETE: ${endpoint}`);
return new Promise((resolve, reject) => {
this.http
.delete(this.base + endpoint, this.buildOptions(options))
......
......@@ -26,9 +26,6 @@ export class CookieHttpInterceptorService implements HttpInterceptor {
): Observable<HttpEvent<any>> {
request = request.clone({ withCredentials: true });
if (!isPlatformBrowser(this.platformId)) {
// Be careful! This should only be done on the server side!!
// hrow xhr2.prototype;
// xhr2.prototype._restrictedHeaders = {};
let req: express.Request = this.injector.get(REQUEST);
let rootDomain = req.hostname
.split('.')
......@@ -42,8 +39,6 @@ export class CookieHttpInterceptorService implements HttpInterceptor {
},
''
);
console.log(cookieString);
// throw xhr2.prototype;
request = request.clone({
headers: request.headers.set('Cookie', cookieString),
});
......
......@@ -116,7 +116,7 @@ export const MINDS_PROVIDERS: any[] = [
{
provide: TranslationService,
useFactory: TranslationService._,
deps: [Client, Storage],
deps: [Client, Storage, PLATFORM_ID],
},
{
provide: RichEmbedService,
......@@ -132,7 +132,7 @@ export const MINDS_PROVIDERS: any[] = [
{
provide: AnalyticsService,
useFactory: AnalyticsService._,
deps: [Router, Client, SiteService],
deps: [Router, Client, SiteService, PLATFORM_ID],
},
{
provide: Navigation,
......@@ -142,7 +142,7 @@ export const MINDS_PROVIDERS: any[] = [
{
provide: WalletService,
useFactory: WalletService._,
deps: [Session, Client, SocketsService],
deps: [Session, Client, SocketsService, PLATFORM_ID],
},
{
provide: AttachmentService,
......
import { Inject } from '@angular/core';
import { Inject, PLATFORM_ID } from '@angular/core';
import { Client } from './api';
import { Storage } from './storage';
import { isPlatformBrowser } from '@angular/common';
export class TranslationService {
private defaultLanguage: string;
private languagesReady: Promise<any>;
static _(client: Client, storage: Storage) {
return new TranslationService(client, storage);
static _(client: Client, storage: Storage, platformId) {
return new TranslationService(client, storage, platformId);
}
constructor(
@Inject(Client) private clientService: Client,
@Inject(Storage) private storage: Storage
@Inject(Storage) private storage: Storage,
@Inject(PLATFORM_ID) platformId
) {
this.defaultLanguage = 'en'; // TODO: Set to get translated names (when i18n is in place)
this.load();
if (isPlatformBrowser(platformId)) this.load();
}
getLanguages(): Promise<any> {
......
import { Inject, Injector, EventEmitter } from '@angular/core';
import { Inject, EventEmitter, PLATFORM_ID } from '@angular/core';
import { Subscription } from 'rxjs';
import { Client } from './api';
import { Session } from './session';
import { SocketsService } from './sockets';
import { isPlatformBrowser } from '@angular/common';
export class WalletService {
points: number | null = null;
......@@ -15,25 +16,33 @@ export class WalletService {
}>();
private pointsTxSubscription: Subscription;
static _(session: Session, client: Client, sockets: SocketsService) {
return new WalletService(session, client, sockets);
static _(
session: Session,
client: Client,
sockets: SocketsService,
platformId
) {
return new WalletService(session, client, sockets, platformId);
}
constructor(
@Inject(Session) public session: Session,
@Inject(Client) public client: Client,
@Inject(SocketsService) private sockets: SocketsService
@Inject(SocketsService) private sockets: SocketsService,
@Inject(PLATFORM_ID) platformId
) {
this.getBalance();
this.session.isLoggedIn(is => {
if (is) {
this.getBalance(true);
} else {
this.points = null;
this.sync();
}
});
if (isPlatformBrowser(platformId)) {
this.getBalance();
this.session.isLoggedIn(is => {
if (is) {
this.getBalance(true);
} else {
this.points = null;
this.sync();
}
});
}
this.listen();
}
......
Please register or to comment