text
stringlengths 3
1.05M
|
|---|
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017-2019 The Sato Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SATO_QT_OPTIONSMODEL_H
#define SATO_QT_OPTIONSMODEL_H
#include "amount.h"
#include <QAbstractListModel>
QT_BEGIN_NAMESPACE
class QNetworkProxy;
QT_END_NAMESPACE
/** Interface from Qt to configuration data structure for Sato client.
To Qt, the options are presented as a list with the different options
laid out vertically.
This can be changed to a tree once the settings become sufficiently
complex.
*/
class OptionsModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit OptionsModel(QObject *parent = 0, bool resetSettings = false);
enum OptionID {
StartAtStartup, // bool
HideTrayIcon, // bool
MinimizeToTray, // bool
MapPortUPnP, // bool
MinimizeOnClose, // bool
ProxyUse, // bool
ProxyIP, // QString
ProxyPort, // int
ProxyUseTor, // bool
ProxyIPTor, // QString
ProxyPortTor, // int
DisplayUnit, // SatoUnits::Unit
ThirdPartyTxUrls, // QString
Language, // QString
CoinControlFeatures, // bool
ThreadsScriptVerif, // int
DatabaseCache, // int
SpendZeroConfChange, // bool
Listen, // bool
CustomFeeFeatures, // bool
DarkModeEnabled, // bool
OptionIDRowCount,
};
void Init(bool resetSettings = false);
void Reset();
int rowCount(const QModelIndex & parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);
/** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */
void setDisplayUnit(const QVariant &value);
/* Explicit getters */
bool getHideTrayIcon() const { return fHideTrayIcon; }
bool getMinimizeToTray() const { return fMinimizeToTray; }
bool getMinimizeOnClose() const { return fMinimizeOnClose; }
int getDisplayUnit() const { return nDisplayUnit; }
QString getThirdPartyTxUrls() const { return strThirdPartyTxUrls; }
bool getProxySettings(QNetworkProxy& proxy) const;
bool getCoinControlFeatures() const { return fCoinControlFeatures; }
bool getCustomFeeFeatures() const { return fCustomFeeFeatures; }
bool getDarkModeEnabled() const { return fDarkModeEnabled; }
const QString& getOverriddenByCommandLine() { return strOverriddenByCommandLine; }
/* Restart flag helper */
void setRestartRequired(bool fRequired);
bool isRestartRequired() const;
private:
/* Qt-only settings */
bool fHideTrayIcon;
bool fMinimizeToTray;
bool fMinimizeOnClose;
QString language;
int nDisplayUnit;
QString strThirdPartyTxUrls;
bool fCoinControlFeatures;
/** SATO START*/
bool fCustomFeeFeatures;
bool fDarkModeEnabled;
/** SATO END*/
/* settings that were overridden by command-line */
QString strOverriddenByCommandLine;
// Add option to list of GUI options overridden through command line/config file
void addOverriddenOption(const std::string &option);
// Check settings version and upgrade default values if required
void checkAndMigrate();
Q_SIGNALS:
void displayUnitChanged(int unit);
void coinControlFeaturesChanged(bool);
void customFeeFeaturesChanged(bool);
void hideTrayIconChanged(bool);
};
#endif // SATO_QT_OPTIONSMODEL_H
|
'use strict'
import { spawn } from 'child_process'
import Brain from '@/core/brain'
describe('brain', () => {
describe('constructor()', () => {
test('creates a new instance of Brain', () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
expect(brain).toBeInstanceOf(Brain)
})
})
describe('talk()', () => {
test('does not emit answer to the client when the speech is empty', () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
brain.talk('')
expect(brain.socket.emit).toHaveBeenCalledTimes(0)
})
test('emits string answer to the client', () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
brain.tts = { add: jest.fn() }
brain.talk('Hello world')
expect(brain.tts.add).toHaveBeenCalledTimes(1)
expect(brain.socket.emit).toHaveBeenCalledTimes(1)
})
})
describe('wernicke()', () => {
test('picks specific string according to object properties', () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
expect(brain.wernicke('errors', 'not_found', { })).toBe('Sorry, it seems I cannot find that')
})
test('picks random string from an array', () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
expect(global.enExpressions.answers.random_errors).toIncludeAnyMembers([brain.wernicke('random_errors', '', { })])
})
})
describe('execute()', () => {
test('asks to repeat', async () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
brain.talk = jest.fn()
await brain.execute({ classification: { confidence: 0.1 } })
const [string] = brain.talk.mock.calls
expect(global.enExpressions.answers.random_not_sure)
.toIncludeAnyMembers([string[0].substr(0, (string[0].length - 1))])
})
test('creates child process', async () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
brain.tts = {
synthesizer: jest.fn(),
default: jest.fn(),
save: jest.fn(),
add: jest.fn()
}
const obj = {
query: 'Hello',
entities: [],
classification: {
package: 'leon',
module: 'greeting',
action: 'run',
confidence: 0.9
}
}
await brain.execute(obj)
expect(brain.process).toEqual({ })
})
test('executes module', async () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
brain.talk = jest.fn()
const obj = {
query: 'Is github.com up?',
entities: [{
sourceText: 'github.com',
utteranceText: 'github.com',
entity: 'url',
resolution: {
value: 'github.com'
}
}],
classification: {
package: 'checker',
module: 'isitdown',
action: 'run',
confidence: 0.9
}
}
await brain.execute(obj)
expect(brain.talk).toHaveBeenCalled()
})
test('rejects promise because of spawn failure', async () => {
const brain = new Brain({ emit: jest.fn() }, 'en')
brain.talk = jest.fn()
const obj = {
query: 'Hello',
entities: [],
classification: {
package: 'leon',
module: 'greeting',
action: 'run',
confidence: 0.9
}
}
brain.process = spawn('pipenv', ['run', 'python', `${global.paths.packages}/fake-main-to-test.py`, 'en',
obj.classification.package, obj.classification.module, obj.query])
try {
await brain.execute(obj)
} catch (e) {
expect(e.type).toBe('error')
expect(brain.talk).toHaveBeenCalledTimes(1)
}
})
})
})
|
//
// GITPackFileVersion2.h
// CocoaGit
//
// Created by Geoffrey Garside on 04/11/2008.
// Copyright 2008 ManicPanda.com. All rights reserved.
//
#import "GITPackFile.h"
@class GITPackIndex;
@interface GITPackFileVersion2 : GITPackFile
{
NSString * path;
NSData * data;
GITPackIndex * index;
NSUInteger numberOfObjects;
}
// These may be removed at a later date.
@property(readonly,copy) NSString * path;
@property(readonly,retain) NSData * data;
@property(readonly,retain) GITPackIndex * index;
@end
|
import("etherpad.log");
import("plugins.realTimeRecentChanges.hooks");
import("plugins.realTimeRecentChanges.static.js.main");
function realTimeRecentChangesInit() {
this.hooks = ['handlePath', 'docbarItemsSearch'];
this.client = new main.realTimeRecentChangesInit();
this.description = 'Real-Time Recent Changes modifies the twitterStyleTags Tag Browser to update in real time.';
this.handlePath = hooks.handlePath;
this.docbarItemsSearch = hooks.docbarItemsSearch;
this.install = install;
this.uninstall = uninstall;
}
function install() {
log.info("Installing Real-Time Recent Changes plugin.");
}
function uninstall() {
log.info("Uninstalling Real-Time Recent Changes plugin.");
}
|
import pydoc
import textwrap
import sys
import cStringIO
# window has to be a global so that the main bpython.py can load it and
# alter its state and share it with the interpreter being used for the
# actual user input, I couldn't think of another way of doing this.
window = None
def _help(obj):
"""Wrapper for the regular help() function but with a ghetto
PAGER since curses + less = :(
As per the vanilla help(), this function special-cases for str,
so you can do help('isinstance') or help(isinstance) and get the
same result.
"""
io = cStringIO.StringIO()
doc = pydoc.TextDoc()
helper = pydoc.Helper(None, io)
rows, columns = window.getmaxyx()
rows -= 3
columns -= 1
output = None
# Copied and pasted from Lib/pydoc.py and fiddled with
# so it works fine with bpython. As far as I can tell
# the bpython help is no compliant with the vanilla help.
# Please let me know if you find this to be untrue.
if type(obj) is type(''):
if obj == 'help':
helper.intro()
elif obj == 'keywords':
helper.listkeywords()
elif obj == 'topics':
helper.listtopics()
elif obj == 'modules':
helper.listmodules()
elif obj[:8] == 'modules ':
helper.listmodules(split(obj)[1])
elif obj in helper.keywords:
helper.showtopic(obj)
elif obj in helper.topics:
helper.showtopic(obj)
elif obj:
output = doc.document(eval(obj))
#######################
else:
output = doc.document(obj)
if not output:
output = "No help found for %s" % obj
return
if output is None:
output = io.getvalue()
io.close()
if not output:
return
output = output.replace('\t', ' ')
if '\n' in output:
output = output.replace('\n\n', '\n')
output = output.split('\n')
else:
output = [output]
paragraphs = []
for o in output:
paragraphs.append(textwrap.wrap(o, columns))
i = 0
for j, paragraph in enumerate(paragraphs):
for line in paragraph:
sys.stdout.write(line + '\n')
i += 1
# This is a little unclear, but it just waits for a
# keypress when the a page worth of text has been
# displayed and returns if 'q' is pressed:
if not i % rows and not wait_for_key():
return
def wait_for_key():
"""Block until a key is pressed for the ghetto paging."""
q = True
window.addstr("Press any key, q to cancel.")
while True:
c = window.getch()
if c and c == ord('q'):
q = False
if c:
break
clear_line()
return q
def clear_line():
y = window.getyx()[0]
window.move(y, 0)
window.clrtoeol()
# vim: sw=4 ts=4 sts=4 ai et
|
/*
=== Complete Variable and Function Definitions ===
*/
const customName = document.getElementById('customName')
const randomize = document.querySelector('.randomize')
const story = document.querySelector('.story')
function randomValueFromArray(array) {
const random = Math.floor(Math.random() * array.length)
return array[random]
}
/*
=== Raw Text Strings ===
*/
let storyText = `It was 94 fahrenheit outside, so ${insertx}: went for a walk. When they got to ${inserty}, they stared in horror for a few moments, then ${insertz}. Bob saw the whole thing, but was not surprised — ${insertx} weighs 300 pounds, and it was a hot day.`
const instertx = ['Willy the Goblin', 'Big Daddy', 'Father Christmas']
const insterty = ['the soup kitchen', 'Disneyland', 'the White House']
const insertz = ['spontaneously combusted', 'melted into a puddle on the sidewalk', 'turned into a slug and crawled away']
/*
=== Event Listener and Partial Function Definition ===
*/
randomize.addEventListener('click', result)
let newStory = storyText
const xItem = randomValueFromArray(insertx)
const yItem = randomValueFromArray(inserty)
const zItem = randomValueFromArray(insertz)
function result() {
if (customName.value !== '') {
let name = customName.value
}
if (document.getElementById("uk").checked) {
let weight = Math.round(300)
let temperature = Math.round(94)
}
story.textContent = ;
story.getElementsByClassName.visibility = 'visible'
}
|
import os
import tempfile
from django.conf import settings
CUSTOM_MODULES = {
'django.db.backends.mysql': 'backupdb.dbbackends.mysql.MysqlDump',
}
# Custom Settings
# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB - 104857600
# 250MB - 214958080
# 500MB - 429916160
TMP_FILE_MAX_SIZE = getattr(settings, 'DBBACKUP_TMP_FILE_MAX_SIZE', 10485760)
TMP_FILE_READ_SIZE = getattr(settings, 'DBBACKUP_TMP_FILE_READ_SIZE', 1024 * 1000)
CONNECTORS = getattr(settings, 'DATABASES', {})
DATABASES = getattr(settings, 'DATABASES', list(settings.DATABASES.keys()))
PROJ_DIR = getattr(settings, 'BASE_DIR')
# define temporary directory or get default system tmp dir
TMP_DIR = getattr(settings, 'TMP_DIR', tempfile.gettempdir())
DUMP_DIR = getattr(settings, 'DUMP_DIR', str(PROJ_DIR))
|
from django.core.exceptions import ImproperlyConfigured
import pytest
from tests.factories import AttachmentFactory, AttachmentFileTypeFactory
from unicef_attachments import utils
from unicef_attachments.models import AttachmentFlat, FileType
from unicef_attachments.permissions import AttachmentPermissions
from demo.sample.models import AttachmentFlatOverride
from demo.sample.permissions import AttachmentPermOverride
from demo.sample.utils import denormalize, filepath_prefix
pytestmark = pytest.mark.django_db
def test_get_filepath_prefix_func_default():
assert utils.get_filepath_prefix_func() == utils._filepath_prefix
def test_get_filepath_prefix_func_override(settings):
settings.ATTACHMENT_FILEPATH_PREFIX_FUNC = "demo.sample.utils.filepath_prefix"
assert utils.get_filepath_prefix_func() == filepath_prefix
def test_get_filepath_prefix_func_invalid(settings):
settings.ATTACHMENT_FILEPATH_PREFIX_FUNC = "demo.wrong.filepath_prefix"
with pytest.raises(ImproperlyConfigured):
utils.get_filepath_prefix_func()
def test_get_attachment_flat_model_default():
assert utils.get_attachment_flat_model() == AttachmentFlat
def test_get_attachment_flat_model_override(settings):
settings.ATTACHMENT_FLAT_MODEL = "demo.sample.models.AttachmentFlatOverride"
assert utils.get_attachment_flat_model() == AttachmentFlatOverride
def test_get_attachment_flat_model_invalid(settings):
settings.ATTACHMENT_FLAT_MODEL = "demo.sample.wrong.AttachmentFlatOverride"
with pytest.raises(ImproperlyConfigured):
utils.get_attachment_flat_model()
def test_get_attachment_permissions_default():
assert utils.get_attachment_permissions() == AttachmentPermissions
def test_get_attachment_permissions_override(settings):
settings.ATTACHMENT_PERMISSIONS = "demo.sample.permissions.AttachmentPermOverride"
assert utils.get_attachment_permissions() == AttachmentPermOverride
def test_get_attachment_permissions_invalid(settings):
settings.ATTACHMENT_PERMISSIONS = "demo.sample.wrong.AttachmentPermOverride"
with pytest.raises(ImproperlyConfigured):
utils.get_attachment_permissions()
def test_get_denormalize_func_default():
assert utils.get_denormalize_func() == utils.denormalize_attachment
def test_get_denormalize_func_override(settings):
settings.ATTACHMENT_DENORMALIZE_FUNC = "demo.sample.utils.denormalize"
assert utils.get_denormalize_func() == denormalize
def test_get_denormalize_func_invalid(settings):
settings.ATTACHMENT_DENORMALIZE_FUNC = "demo.sample.wrong.denormalize"
with pytest.raises(ImproperlyConfigured):
utils.get_denormalize_func()
def test_get_matching_key(file_type):
key = (file_type.label.lower(), file_type.name.lower())
# name matches
name_key = ("something", file_type.name.lower())
assert name_key == utils.get_matching_key(file_type, [name_key])
# label matches
label_key = (file_type.label.lower(), "something")
assert label_key == utils.get_matching_key(file_type, [label_key])
# no matches
assert key == utils.get_matching_key(file_type, [("some", "thing")])
def test_cleanup_file_types():
file_type_1 = AttachmentFileTypeFactory(
label="Other",
name="something",
)
file_type_2 = AttachmentFileTypeFactory(
label="Other",
name="different",
group=["ft2"],
)
file_type_3 = AttachmentFileTypeFactory(
label="PD",
name="pd",
group=["ft3"],
)
file_type_4 = AttachmentFileTypeFactory(
label="FT4",
name="something",
group=["ft4"],
)
attachment_1 = AttachmentFactory(file_type=file_type_1)
attachment_2 = AttachmentFactory(file_type=file_type_2)
attachment_3 = AttachmentFactory(file_type=file_type_3)
attachment_4 = AttachmentFactory(file_type=file_type_4)
utils.cleanup_filetypes()
attachment_1.refresh_from_db()
assert attachment_1.file_type == file_type_1
attachment_2.refresh_from_db()
assert attachment_2.file_type == file_type_1
attachment_3.refresh_from_db()
assert attachment_3.file_type == file_type_3
attachment_4.refresh_from_db()
assert attachment_4.file_type == file_type_1
assert not FileType.objects.filter(pk=file_type_2.pk).exists()
assert not FileType.objects.filter(pk=file_type_4.pk).exists()
file_type_1.refresh_from_db()
assert file_type_1.group == ["ft2", "ft4"]
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ChromotingClient is the controller for the Client implementation.
#ifndef REMOTING_CLIENT_CHROMOTING_CLIENT_H_
#define REMOTING_CLIENT_CHROMOTING_CLIENT_H_
#include <string>
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "remoting/client/client_config.h"
#include "remoting/client/chromoting_stats.h"
#include "remoting/protocol/client_stub.h"
#include "remoting/protocol/clipboard_stub.h"
#include "remoting/protocol/connection_to_host.h"
#include "remoting/protocol/input_stub.h"
#include "remoting/protocol/video_stub.h"
namespace base {
class SingleThreadTaskRunner;
} // namespace base
namespace remoting {
namespace protocol {
class TransportFactory;
} // namespace protocol
class AudioDecodeScheduler;
class AudioPlayer;
class ClientContext;
class ClientUserInterface;
class FrameConsumerProxy;
class FrameProducer;
class VideoRenderer;
class SignalStrategy;
class ChromotingClient : public protocol::ConnectionToHost::HostEventCallback,
public protocol::ClientStub {
public:
// |audio_player| may be null, in which case audio will not be requested.
ChromotingClient(const ClientConfig& config,
ClientContext* client_context,
protocol::ConnectionToHost* connection,
ClientUserInterface* user_interface,
VideoRenderer* video_renderer,
scoped_ptr<AudioPlayer> audio_player);
virtual ~ChromotingClient();
// Start the client. Must be called on the main thread. |signal_strategy|
// must outlive the client.
void Start(SignalStrategy* signal_strategy,
scoped_ptr<protocol::TransportFactory> transport_factory);
// ClientStub implementation.
virtual void SetCapabilities(
const protocol::Capabilities& capabilities) OVERRIDE;
virtual void SetPairingResponse(
const protocol::PairingResponse& pairing_response) OVERRIDE;
virtual void DeliverHostMessage(
const protocol::ExtensionMessage& message) OVERRIDE;
// ClipboardStub implementation for receiving clipboard data from host.
virtual void InjectClipboardEvent(
const protocol::ClipboardEvent& event) OVERRIDE;
// CursorShapeStub implementation for receiving cursor shape updates.
virtual void SetCursorShape(
const protocol::CursorShapeInfo& cursor_shape) OVERRIDE;
// ConnectionToHost::HostEventCallback implementation.
virtual void OnConnectionState(
protocol::ConnectionToHost::State state,
protocol::ErrorCode error) OVERRIDE;
virtual void OnConnectionReady(bool ready) OVERRIDE;
virtual void OnRouteChanged(const std::string& channel_name,
const protocol::TransportRoute& route) OVERRIDE;
private:
// Called when the connection is authenticated.
void OnAuthenticated();
// Called when all channels are connected.
void OnChannelsConnected();
// The following are not owned by this class.
ClientConfig config_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
protocol::ConnectionToHost* connection_;
ClientUserInterface* user_interface_;
VideoRenderer* video_renderer_;
scoped_ptr<AudioDecodeScheduler> audio_decode_scheduler_;
// If non-NULL, this is called when the client is done.
base::Closure client_done_;
// The set of all capabilities supported by the host.
std::string host_capabilities_;
// True if |protocol::Capabilities| message has been received.
bool host_capabilities_received_;
// Record the statistics of the connection.
ChromotingStats stats_;
// WeakPtr used to avoid tasks accessing the client after it is deleted.
base::WeakPtr<ChromotingClient> weak_ptr_;
base::WeakPtrFactory<ChromotingClient> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ChromotingClient);
};
} // namespace remoting
#endif // REMOTING_CLIENT_CHROMOTING_CLIENT_H_
|
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class Link(Base):
"""This object holds the LACP link configuration.
The Link class encapsulates a list of link resources that are managed by the user.
A list of resources can be retrieved from the server using the Link.find() method.
The list can be managed by using the Link.add() and Link.remove() methods.
"""
__slots__ = ()
_SDM_NAME = 'link'
_SDM_ATT_MAP = {
'ActorKey': 'actorKey',
'ActorPortNumber': 'actorPortNumber',
'ActorPortPriority': 'actorPortPriority',
'ActorSystemId': 'actorSystemId',
'ActorSystemPriority': 'actorSystemPriority',
'AdministrativeKey': 'administrativeKey',
'AggregationFlagState': 'aggregationFlagState',
'AutoPickPortMac': 'autoPickPortMac',
'CollectingFlag': 'collectingFlag',
'CollectorMaxDelay': 'collectorMaxDelay',
'DistributingFlag': 'distributingFlag',
'Enabled': 'enabled',
'InterMarkerPduDelay': 'interMarkerPduDelay',
'LacpActivity': 'lacpActivity',
'LacpTimeout': 'lacpTimeout',
'LacpduPeriodicTimeInterval': 'lacpduPeriodicTimeInterval',
'MarkerRequestMode': 'markerRequestMode',
'MarkerResponseWaitTime': 'markerResponseWaitTime',
'PortMac': 'portMac',
'SendMarkerRequestOnLagChange': 'sendMarkerRequestOnLagChange',
'SendPeriodicMarkerRequest': 'sendPeriodicMarkerRequest',
'SupportRespondingToMarker': 'supportRespondingToMarker',
'SyncFlag': 'syncFlag',
'UpdateRequired': 'updateRequired',
}
def __init__(self, parent):
super(Link, self).__init__(parent)
@property
def ActorKey(self):
"""
Returns
-------
- number: The operational Key value assigned to the port by the Actor. This is a 2 byte field with a default of 1. Minimum value is 0, maximum value is 65535.
"""
return self._get_attribute(self._SDM_ATT_MAP['ActorKey'])
@ActorKey.setter
def ActorKey(self, value):
self._set_attribute(self._SDM_ATT_MAP['ActorKey'], value)
@property
def ActorPortNumber(self):
"""
Returns
-------
- number: The port number assigned to the port by the Actor (the System sending the PDU). It is a 2 byte field with a default of 1. Min: 0, Max: 65535.
"""
return self._get_attribute(self._SDM_ATT_MAP['ActorPortNumber'])
@ActorPortNumber.setter
def ActorPortNumber(self, value):
self._set_attribute(self._SDM_ATT_MAP['ActorPortNumber'], value)
@property
def ActorPortPriority(self):
"""
Returns
-------
- number: This field specifies the port priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
"""
return self._get_attribute(self._SDM_ATT_MAP['ActorPortPriority'])
@ActorPortPriority.setter
def ActorPortPriority(self, value):
self._set_attribute(self._SDM_ATT_MAP['ActorPortPriority'], value)
@property
def ActorSystemId(self):
"""
Returns
-------
- str: This field specifies the system identifier for the link Actor. It is a 6 byte field, with a default of 00-00-00-00-00-01. Min: 00-00-00-00-00-00, Max: FF-FF-FF-FF-FF-FF.
"""
return self._get_attribute(self._SDM_ATT_MAP['ActorSystemId'])
@ActorSystemId.setter
def ActorSystemId(self, value):
self._set_attribute(self._SDM_ATT_MAP['ActorSystemId'], value)
@property
def ActorSystemPriority(self):
"""
Returns
-------
- number: This field specifies the system priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
"""
return self._get_attribute(self._SDM_ATT_MAP['ActorSystemPriority'])
@ActorSystemPriority.setter
def ActorSystemPriority(self, value):
self._set_attribute(self._SDM_ATT_MAP['ActorSystemPriority'], value)
@property
def AdministrativeKey(self):
"""
Returns
-------
- number: This field controls the aggregation of ports of the same system with similar Actor Key.
"""
return self._get_attribute(self._SDM_ATT_MAP['AdministrativeKey'])
@AdministrativeKey.setter
def AdministrativeKey(self, value):
self._set_attribute(self._SDM_ATT_MAP['AdministrativeKey'], value)
@property
def AggregationFlagState(self):
"""
Returns
-------
- str(disable | auto): If enabled, sets the port status to automatically allow aggregation.
"""
return self._get_attribute(self._SDM_ATT_MAP['AggregationFlagState'])
@AggregationFlagState.setter
def AggregationFlagState(self, value):
self._set_attribute(self._SDM_ATT_MAP['AggregationFlagState'], value)
@property
def AutoPickPortMac(self):
"""
Returns
-------
- bool: If true the source MAC is the interface MAC address.
"""
return self._get_attribute(self._SDM_ATT_MAP['AutoPickPortMac'])
@AutoPickPortMac.setter
def AutoPickPortMac(self, value):
self._set_attribute(self._SDM_ATT_MAP['AutoPickPortMac'], value)
@property
def CollectingFlag(self):
"""
Returns
-------
- bool: If true, the actor port state Collecting is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent
"""
return self._get_attribute(self._SDM_ATT_MAP['CollectingFlag'])
@CollectingFlag.setter
def CollectingFlag(self, value):
self._set_attribute(self._SDM_ATT_MAP['CollectingFlag'], value)
@property
def CollectorMaxDelay(self):
"""
Returns
-------
- number: The maximum time in microseconds that the Frame Collector may delay the delivery of a frame received from an Aggregator to its MAC client. This is a 2 byte field with a default 0. Min: 0, Max: 65535.
"""
return self._get_attribute(self._SDM_ATT_MAP['CollectorMaxDelay'])
@CollectorMaxDelay.setter
def CollectorMaxDelay(self, value):
self._set_attribute(self._SDM_ATT_MAP['CollectorMaxDelay'], value)
@property
def DistributingFlag(self):
"""
Returns
-------
- bool: If true, the actor port state Distributing is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
"""
return self._get_attribute(self._SDM_ATT_MAP['DistributingFlag'])
@DistributingFlag.setter
def DistributingFlag(self, value):
self._set_attribute(self._SDM_ATT_MAP['DistributingFlag'], value)
@property
def Enabled(self):
"""
Returns
-------
- bool: If true, the link is enabled.
"""
return self._get_attribute(self._SDM_ATT_MAP['Enabled'])
@Enabled.setter
def Enabled(self, value):
self._set_attribute(self._SDM_ATT_MAP['Enabled'], value)
@property
def InterMarkerPduDelay(self):
"""
Returns
-------
- str: The time gap in seconds between two consecutive Marker PDUs when transmitted periodically.
"""
return self._get_attribute(self._SDM_ATT_MAP['InterMarkerPduDelay'])
@InterMarkerPduDelay.setter
def InterMarkerPduDelay(self, value):
self._set_attribute(self._SDM_ATT_MAP['InterMarkerPduDelay'], value)
@property
def LacpActivity(self):
"""
Returns
-------
- str(active | passive): Sets the value of LACPs Actor activity, either passive or active.
"""
return self._get_attribute(self._SDM_ATT_MAP['LacpActivity'])
@LacpActivity.setter
def LacpActivity(self, value):
self._set_attribute(self._SDM_ATT_MAP['LacpActivity'], value)
@property
def LacpTimeout(self):
"""
Returns
-------
- number: This timer is used to detect whether received protocol information has expired. The user can provide a custom value from 1 to 65535.
"""
return self._get_attribute(self._SDM_ATT_MAP['LacpTimeout'])
@LacpTimeout.setter
def LacpTimeout(self, value):
self._set_attribute(self._SDM_ATT_MAP['LacpTimeout'], value)
@property
def LacpduPeriodicTimeInterval(self):
"""
Returns
-------
- number: This field defines how frequently LACPDUs are sent to the link partner. The user can provide a custom values from 1 to 65535, in seconds
"""
return self._get_attribute(self._SDM_ATT_MAP['LacpduPeriodicTimeInterval'])
@LacpduPeriodicTimeInterval.setter
def LacpduPeriodicTimeInterval(self, value):
self._set_attribute(self._SDM_ATT_MAP['LacpduPeriodicTimeInterval'], value)
@property
def MarkerRequestMode(self):
"""
Returns
-------
- str(fixed | random): Sets the marker request mode for the Actor link.In either case, the mode parameters are specified in Marker Request Frequency.
"""
return self._get_attribute(self._SDM_ATT_MAP['MarkerRequestMode'])
@MarkerRequestMode.setter
def MarkerRequestMode(self, value):
self._set_attribute(self._SDM_ATT_MAP['MarkerRequestMode'], value)
@property
def MarkerResponseWaitTime(self):
"""
Returns
-------
- number: The number of seconds to wait for Marker Response after sending a Marker Request. After this time, the Marker Response Timeout Count is incremented. If a marker response does arrive for the request after this timeout, it is not considered as a legitimate response.
"""
return self._get_attribute(self._SDM_ATT_MAP['MarkerResponseWaitTime'])
@MarkerResponseWaitTime.setter
def MarkerResponseWaitTime(self, value):
self._set_attribute(self._SDM_ATT_MAP['MarkerResponseWaitTime'], value)
@property
def PortMac(self):
"""
Returns
-------
- str: specifies the port MAC address.
"""
return self._get_attribute(self._SDM_ATT_MAP['PortMac'])
@PortMac.setter
def PortMac(self, value):
self._set_attribute(self._SDM_ATT_MAP['PortMac'], value)
@property
def SendMarkerRequestOnLagChange(self):
"""
Returns
-------
- bool: If true, this checkbox causes LACP to send a Marker PDU on the following situations: 1) System Priority has been modified; 2) System Id has been modified; 3) Actor Key has been modified; 4) Port Number/Port Priority has been modified while we are in Individual mode.
"""
return self._get_attribute(self._SDM_ATT_MAP['SendMarkerRequestOnLagChange'])
@SendMarkerRequestOnLagChange.setter
def SendMarkerRequestOnLagChange(self, value):
self._set_attribute(self._SDM_ATT_MAP['SendMarkerRequestOnLagChange'], value)
@property
def SendPeriodicMarkerRequest(self):
"""
Returns
-------
- bool: If true, Marker Request PDUs are periodically after both actor and partner are IN SYNC and our state is aggregated. The moment we come out of this state, the periodic sending of Marker will be stopped.
"""
return self._get_attribute(self._SDM_ATT_MAP['SendPeriodicMarkerRequest'])
@SendPeriodicMarkerRequest.setter
def SendPeriodicMarkerRequest(self, value):
self._set_attribute(self._SDM_ATT_MAP['SendPeriodicMarkerRequest'], value)
@property
def SupportRespondingToMarker(self):
"""
Returns
-------
- bool: If true, LACP doesn't respond to MARKER request PDUs from the partner.
"""
return self._get_attribute(self._SDM_ATT_MAP['SupportRespondingToMarker'])
@SupportRespondingToMarker.setter
def SupportRespondingToMarker(self, value):
self._set_attribute(self._SDM_ATT_MAP['SupportRespondingToMarker'], value)
@property
def SyncFlag(self):
"""
Returns
-------
- str(disable | auto): If enabled, the actor port state is set to True based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
"""
return self._get_attribute(self._SDM_ATT_MAP['SyncFlag'])
@SyncFlag.setter
def SyncFlag(self, value):
self._set_attribute(self._SDM_ATT_MAP['SyncFlag'], value)
@property
def UpdateRequired(self):
"""
Returns
-------
- bool: (read only) If true, an update LAPDU is required for the link.
"""
return self._get_attribute(self._SDM_ATT_MAP['UpdateRequired'])
def update(self, ActorKey=None, ActorPortNumber=None, ActorPortPriority=None, ActorSystemId=None, ActorSystemPriority=None, AdministrativeKey=None, AggregationFlagState=None, AutoPickPortMac=None, CollectingFlag=None, CollectorMaxDelay=None, DistributingFlag=None, Enabled=None, InterMarkerPduDelay=None, LacpActivity=None, LacpTimeout=None, LacpduPeriodicTimeInterval=None, MarkerRequestMode=None, MarkerResponseWaitTime=None, PortMac=None, SendMarkerRequestOnLagChange=None, SendPeriodicMarkerRequest=None, SupportRespondingToMarker=None, SyncFlag=None):
"""Updates link resource on the server.
Args
----
- ActorKey (number): The operational Key value assigned to the port by the Actor. This is a 2 byte field with a default of 1. Minimum value is 0, maximum value is 65535.
- ActorPortNumber (number): The port number assigned to the port by the Actor (the System sending the PDU). It is a 2 byte field with a default of 1. Min: 0, Max: 65535.
- ActorPortPriority (number): This field specifies the port priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
- ActorSystemId (str): This field specifies the system identifier for the link Actor. It is a 6 byte field, with a default of 00-00-00-00-00-01. Min: 00-00-00-00-00-00, Max: FF-FF-FF-FF-FF-FF.
- ActorSystemPriority (number): This field specifies the system priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
- AdministrativeKey (number): This field controls the aggregation of ports of the same system with similar Actor Key.
- AggregationFlagState (str(disable | auto)): If enabled, sets the port status to automatically allow aggregation.
- AutoPickPortMac (bool): If true the source MAC is the interface MAC address.
- CollectingFlag (bool): If true, the actor port state Collecting is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent
- CollectorMaxDelay (number): The maximum time in microseconds that the Frame Collector may delay the delivery of a frame received from an Aggregator to its MAC client. This is a 2 byte field with a default 0. Min: 0, Max: 65535.
- DistributingFlag (bool): If true, the actor port state Distributing is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
- Enabled (bool): If true, the link is enabled.
- InterMarkerPduDelay (str): The time gap in seconds between two consecutive Marker PDUs when transmitted periodically.
- LacpActivity (str(active | passive)): Sets the value of LACPs Actor activity, either passive or active.
- LacpTimeout (number): This timer is used to detect whether received protocol information has expired. The user can provide a custom value from 1 to 65535.
- LacpduPeriodicTimeInterval (number): This field defines how frequently LACPDUs are sent to the link partner. The user can provide a custom values from 1 to 65535, in seconds
- MarkerRequestMode (str(fixed | random)): Sets the marker request mode for the Actor link.In either case, the mode parameters are specified in Marker Request Frequency.
- MarkerResponseWaitTime (number): The number of seconds to wait for Marker Response after sending a Marker Request. After this time, the Marker Response Timeout Count is incremented. If a marker response does arrive for the request after this timeout, it is not considered as a legitimate response.
- PortMac (str): specifies the port MAC address.
- SendMarkerRequestOnLagChange (bool): If true, this checkbox causes LACP to send a Marker PDU on the following situations: 1) System Priority has been modified; 2) System Id has been modified; 3) Actor Key has been modified; 4) Port Number/Port Priority has been modified while we are in Individual mode.
- SendPeriodicMarkerRequest (bool): If true, Marker Request PDUs are periodically after both actor and partner are IN SYNC and our state is aggregated. The moment we come out of this state, the periodic sending of Marker will be stopped.
- SupportRespondingToMarker (bool): If true, LACP doesn't respond to MARKER request PDUs from the partner.
- SyncFlag (str(disable | auto)): If enabled, the actor port state is set to True based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._update(self._map_locals(self._SDM_ATT_MAP, locals()))
def add(self, ActorKey=None, ActorPortNumber=None, ActorPortPriority=None, ActorSystemId=None, ActorSystemPriority=None, AdministrativeKey=None, AggregationFlagState=None, AutoPickPortMac=None, CollectingFlag=None, CollectorMaxDelay=None, DistributingFlag=None, Enabled=None, InterMarkerPduDelay=None, LacpActivity=None, LacpTimeout=None, LacpduPeriodicTimeInterval=None, MarkerRequestMode=None, MarkerResponseWaitTime=None, PortMac=None, SendMarkerRequestOnLagChange=None, SendPeriodicMarkerRequest=None, SupportRespondingToMarker=None, SyncFlag=None):
"""Adds a new link resource on the server and adds it to the container.
Args
----
- ActorKey (number): The operational Key value assigned to the port by the Actor. This is a 2 byte field with a default of 1. Minimum value is 0, maximum value is 65535.
- ActorPortNumber (number): The port number assigned to the port by the Actor (the System sending the PDU). It is a 2 byte field with a default of 1. Min: 0, Max: 65535.
- ActorPortPriority (number): This field specifies the port priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
- ActorSystemId (str): This field specifies the system identifier for the link Actor. It is a 6 byte field, with a default of 00-00-00-00-00-01. Min: 00-00-00-00-00-00, Max: FF-FF-FF-FF-FF-FF.
- ActorSystemPriority (number): This field specifies the system priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
- AdministrativeKey (number): This field controls the aggregation of ports of the same system with similar Actor Key.
- AggregationFlagState (str(disable | auto)): If enabled, sets the port status to automatically allow aggregation.
- AutoPickPortMac (bool): If true the source MAC is the interface MAC address.
- CollectingFlag (bool): If true, the actor port state Collecting is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent
- CollectorMaxDelay (number): The maximum time in microseconds that the Frame Collector may delay the delivery of a frame received from an Aggregator to its MAC client. This is a 2 byte field with a default 0. Min: 0, Max: 65535.
- DistributingFlag (bool): If true, the actor port state Distributing is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
- Enabled (bool): If true, the link is enabled.
- InterMarkerPduDelay (str): The time gap in seconds between two consecutive Marker PDUs when transmitted periodically.
- LacpActivity (str(active | passive)): Sets the value of LACPs Actor activity, either passive or active.
- LacpTimeout (number): This timer is used to detect whether received protocol information has expired. The user can provide a custom value from 1 to 65535.
- LacpduPeriodicTimeInterval (number): This field defines how frequently LACPDUs are sent to the link partner. The user can provide a custom values from 1 to 65535, in seconds
- MarkerRequestMode (str(fixed | random)): Sets the marker request mode for the Actor link.In either case, the mode parameters are specified in Marker Request Frequency.
- MarkerResponseWaitTime (number): The number of seconds to wait for Marker Response after sending a Marker Request. After this time, the Marker Response Timeout Count is incremented. If a marker response does arrive for the request after this timeout, it is not considered as a legitimate response.
- PortMac (str): specifies the port MAC address.
- SendMarkerRequestOnLagChange (bool): If true, this checkbox causes LACP to send a Marker PDU on the following situations: 1) System Priority has been modified; 2) System Id has been modified; 3) Actor Key has been modified; 4) Port Number/Port Priority has been modified while we are in Individual mode.
- SendPeriodicMarkerRequest (bool): If true, Marker Request PDUs are periodically after both actor and partner are IN SYNC and our state is aggregated. The moment we come out of this state, the periodic sending of Marker will be stopped.
- SupportRespondingToMarker (bool): If true, LACP doesn't respond to MARKER request PDUs from the partner.
- SyncFlag (str(disable | auto)): If enabled, the actor port state is set to True based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
Returns
-------
- self: This instance with all currently retrieved link resources using find and the newly added link resources available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._create(self._map_locals(self._SDM_ATT_MAP, locals()))
def remove(self):
"""Deletes all the contained link resources in this instance from the server.
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
self._delete()
def find(self, ActorKey=None, ActorPortNumber=None, ActorPortPriority=None, ActorSystemId=None, ActorSystemPriority=None, AdministrativeKey=None, AggregationFlagState=None, AutoPickPortMac=None, CollectingFlag=None, CollectorMaxDelay=None, DistributingFlag=None, Enabled=None, InterMarkerPduDelay=None, LacpActivity=None, LacpTimeout=None, LacpduPeriodicTimeInterval=None, MarkerRequestMode=None, MarkerResponseWaitTime=None, PortMac=None, SendMarkerRequestOnLagChange=None, SendPeriodicMarkerRequest=None, SupportRespondingToMarker=None, SyncFlag=None, UpdateRequired=None):
"""Finds and retrieves link resources from the server.
All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve link resources from the server.
To retrieve an exact match ensure the parameter value starts with ^ and ends with $
By default the find method takes no parameters and will retrieve all link resources from the server.
Args
----
- ActorKey (number): The operational Key value assigned to the port by the Actor. This is a 2 byte field with a default of 1. Minimum value is 0, maximum value is 65535.
- ActorPortNumber (number): The port number assigned to the port by the Actor (the System sending the PDU). It is a 2 byte field with a default of 1. Min: 0, Max: 65535.
- ActorPortPriority (number): This field specifies the port priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
- ActorSystemId (str): This field specifies the system identifier for the link Actor. It is a 6 byte field, with a default of 00-00-00-00-00-01. Min: 00-00-00-00-00-00, Max: FF-FF-FF-FF-FF-FF.
- ActorSystemPriority (number): This field specifies the system priority of the link Actor. It is a 2 byte field, with a default or 1. Min: 0, Max: 65535.
- AdministrativeKey (number): This field controls the aggregation of ports of the same system with similar Actor Key.
- AggregationFlagState (str(disable | auto)): If enabled, sets the port status to automatically allow aggregation.
- AutoPickPortMac (bool): If true the source MAC is the interface MAC address.
- CollectingFlag (bool): If true, the actor port state Collecting is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent
- CollectorMaxDelay (number): The maximum time in microseconds that the Frame Collector may delay the delivery of a frame received from an Aggregator to its MAC client. This is a 2 byte field with a default 0. Min: 0, Max: 65535.
- DistributingFlag (bool): If true, the actor port state Distributing is set to true based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
- Enabled (bool): If true, the link is enabled.
- InterMarkerPduDelay (str): The time gap in seconds between two consecutive Marker PDUs when transmitted periodically.
- LacpActivity (str(active | passive)): Sets the value of LACPs Actor activity, either passive or active.
- LacpTimeout (number): This timer is used to detect whether received protocol information has expired. The user can provide a custom value from 1 to 65535.
- LacpduPeriodicTimeInterval (number): This field defines how frequently LACPDUs are sent to the link partner. The user can provide a custom values from 1 to 65535, in seconds
- MarkerRequestMode (str(fixed | random)): Sets the marker request mode for the Actor link.In either case, the mode parameters are specified in Marker Request Frequency.
- MarkerResponseWaitTime (number): The number of seconds to wait for Marker Response after sending a Marker Request. After this time, the Marker Response Timeout Count is incremented. If a marker response does arrive for the request after this timeout, it is not considered as a legitimate response.
- PortMac (str): specifies the port MAC address.
- SendMarkerRequestOnLagChange (bool): If true, this checkbox causes LACP to send a Marker PDU on the following situations: 1) System Priority has been modified; 2) System Id has been modified; 3) Actor Key has been modified; 4) Port Number/Port Priority has been modified while we are in Individual mode.
- SendPeriodicMarkerRequest (bool): If true, Marker Request PDUs are periodically after both actor and partner are IN SYNC and our state is aggregated. The moment we come out of this state, the periodic sending of Marker will be stopped.
- SupportRespondingToMarker (bool): If true, LACP doesn't respond to MARKER request PDUs from the partner.
- SyncFlag (str(disable | auto)): If enabled, the actor port state is set to True based on Tx and Rx state machines. Otherwise, the flag in LACPDU remains reset for all packets sent.
- UpdateRequired (bool): (read only) If true, an update LAPDU is required for the link.
Returns
-------
- self: This instance with matching link resources retrieved from the server available through an iterator or index
Raises
------
- ServerError: The server has encountered an uncategorized error condition
"""
return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
def read(self, href):
"""Retrieves a single instance of link data from the server.
Args
----
- href (str): An href to the instance to be retrieved
Returns
-------
- self: This instance with the link resources from the server available through an iterator or index
Raises
------
- NotFoundError: The requested resource does not exist on the server
- ServerError: The server has encountered an uncategorized error condition
"""
return self._read(href)
|
import discord
class Color(discord.Color):
"""
Colors that aren't part of standard lib colors
"""
def __init__(self, _hex):
super().__init__(_hex)
@classmethod
def light_pink(cls):
return cls(0xFFB6C1)
|
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef __ASM_GENERIC_BASE_BITOPS_SCHED_H_
#define __ASM_GENERIC_BASE_BITOPS_SCHED_H_
#include <base/compiler.h> /* unlikely() */
#include <asm/base/types.h>
/*
* Every architecture must define this function. It's the fastest
* way of searching a 100-bit bitmap. It's guaranteed that at least
* one of the 100 bits is cleared.
*/
static inline int sched_find_first_bit(const unsigned long *b)
{
#if BITS_PER_LONG == 64
if (b[0])
return __ffs(b[0]);
return __ffs(b[1]) + 64;
#elif BITS_PER_LONG == 32
if (b[0])
return __ffs(b[0]);
if (b[1])
return __ffs(b[1]) + 32;
if (b[2])
return __ffs(b[2]) + 64;
return __ffs(b[3]) + 96;
#else
#error BITS_PER_LONG not defined
#endif
}
#endif /* !__ASM_GENERIC_BASE_BITOPS_SCHED_H_ */
|
import compiler from './compiler.js'
import helpers from './helpers'
/**
* Build a word frequency map from a source text.
*/
test('Builds word frequency map (match, project)', async () => {
// Set up loader options.
const options = {
regex: /\b\w+\b/gi,
// Match gets called for every match (must return a value).
match: function (match) {
return match[0]
},
// Project gets called after all matches are found (must return a value).
project: function (matches) {
return matches.reduce((map, word) => {
const lcWord = word.toLowerCase()
map[lcWord] = (map[lcWord] || 0) + 1
return map
}, {})
}
}
const stats = await compiler('data/poems.txt', options)
const output = stats.toJson().modules[0].source
const map = helpers.value(output)
expect(map['all']).toBe(4)
expect(map['elven']).toBe(1)
expect(map['dwarf']).toBe(1)
expect(map['men']).toBe(1)
expect(map['king']).toBe(1)
expect(map['road']).toBe(3)
expect(map['one']).toBe(4)
expect(map['ring']).toBe(3)
expect(map['mordor']).toBe(2)
expect(map['shadows']).toBe(3)
})
/**
* Parse key/value pairs from a source in "key=value" form.
*/
test('Parses key/value pairs (project)', async () => {
// Set up loader options.
const options = {
regex: '^(.+)=(.+)$',
flags: 'mg',
// Match gets called for every match (must return a value).
match: function (match) {
return { key: match[1], value: match[2] }
},
// Project gets called after all matches are found (must return a value).
project: function (result) {
return result.reduce((map, item) => {
try {
map[item.key] = JSON.parse(item.value)
} catch (e) {
map[item.key] = item.value
}
return map
}, {})
}
}
const stats = await compiler('data/keyvals.txt', options)
const output = stats.toJson().modules[0].source
const map = helpers.value(output)
expect(map.name).toBe('Nebula')
expect(map.rank).toBe(10)
expect(map.attributes.length).toBe(5)
expect(map.attributes[4]).toBe('nebulicious')
})
|
import Transport from './Transport';
import TransportError from '../errors/TransportError';
export default class JQueryTransport extends Transport {
/**
* A {@link Transport} implementation for [jQuery]{@link https://jquery.com/}.<br />
* This class supposes that the `jQuery` global object is available.
*
* @constructor
*
* @param [promiseProvider=null] {PromiseProvider} A {@link PromiseProvider} implementation.
*
* @see Transport
*/
constructor(promiseProvider) {
super();
this.promiseProvider = promiseProvider;
}
post(url, headers, data, raw) {
return this.promiseProvider.newPromise(function(resolve, reject) {
jQuery.ajax({
url: url,
method: 'POST',
headers: headers,
data: raw ? data : JSON.stringify(data),
dataType: raw ? undefined : 'json',
processData: false,
jsonp: false
})
.done(resolve)
.fail((xhr, statusText, err) => reject(new TransportError(err, xhr.status, xhr.responseText)));
});
}
}
|
import tkinter
import change_password_window
import login_register_window
import message_window
import change_password_window_actions
import login_register_window_actions
import message_window_actions
class MessengerWindowActions:
def __init__(self, model, view):
self.__model = model
self.__view = view
self.after_id_list = []
self.__key = None
def on_search_button_click(self, event=None):
window = self.__view.get_window(self.__key)[0]
username = window.left_frame.search_entry.get()
if len(username) > 0 and username is not None:
result = self.__model.search_user(username)
if result is not None:
window.left_frame.found_user_list.delete(0, tkinter.END)
for user in result:
window.left_frame.found_user_list.insert(tkinter.END, user)
def on_send_friend_request_button_click(self, event=None):
window = self.__view.get_window(self.__key)[0]
selection = window.left_frame.found_user_list.curselection()
if selection:
username = window.left_frame.found_user_list.get(
window.left_frame.found_user_list.curselection()
)
if not self.__model.send_friend_request(username):
self.__view.create_messagebox("Send Friend Request", "Error: Request has already been sent")
def on_friend_request(self):
window = self.__view.get_window(self.__key)[0]
username = self.__model.get_most_recent_friend_request()
window.right_frame.friend_request_list.insert(tkinter.END, username)
after_id = window.after(
100,
self.on_friend_request
)
self.after_id_list.append(after_id)
def on_messenger_window(self, key, window):
self.__key = key
self.__view.set_window(self.__key, window, self)
result = self.__model.get_friends_list()
for username in result:
window.middle_frame.friends_list.insert(tkinter.END, username)
result = self.__model.get_friend_requests()
for username in result:
window.right_frame.friend_request_list.insert(tkinter.END, username)
username = self.__model.get_username()
window.username_label.config(text="Username: " + username)
self.on_ui_change()
def on_accept_friend_request_button_click(self, event=None):
window = self.__view.get_window(self.__key)[0]
selection = window.right_frame.friend_request_list.curselection()
if selection:
username = window.right_frame.friend_request_list.get(
window.right_frame.friend_request_list.curselection()
)
window.right_frame.friend_request_list.delete(
window.right_frame.friend_request_list.curselection()
)
self.__model.accept_friend_request(username)
window.middle_frame.friends_list.insert(tkinter.END, username)
def on_decline_friend_request_button_click(self):
window = self.__view.get_window(self.__key)[0]
selection = window.right_frame.friend_request_list.curselection()
if selection:
username = window.right_frame.friend_request_list.get(
window.right_frame.friend_request_list.curselection()
)
window.right_frame.friend_request_list.delete(
window.right_frame.friend_request_list.curselection()
)
self.__model.decline_friend_request(username)
def on_ui_change(self):
window = self.__view.get_window(self.__key)[0]
result = self.__model.get_most_recent_change()
if result[0] != "":
window.middle_frame.friends_list.insert(tkinter.END, result[0])
elif result[1] != "":
window.right_frame.friend_request_list.insert(tkinter.END, result[1])
elif result[2] != "":
result = self.__model.get_friends_list()
window.middle_frame.friends_list.delete(0, tkinter.END)
for user in result:
window.right_frame.friend_request_list.insert(tkinter.END, user)
after_id = window.after(
100,
self.on_ui_change
)
self.after_id_list.append(after_id)
def on_change_password_button_click(self):
key = "change_password_window"
if self.__view.window_exists(key):
action = change_password_window_actions.ChangePasswordWindowActions(
self.__model,
self.__view
)
window = change_password_window.ChangePasswordWindow(action)
action.on_change_password_window(key, window)
def on_logout_button_click(self):
self.__model.logout()
self.__delete_after()
self.__view.destroy_window(self.__key)
key = "login_window"
action = login_register_window_actions.LoginRegisterWindowActions(
self.__model,
self.__view
)
window = login_register_window.LoginRegisterWindow(action)
action.on_login_register_window(key, window)
def on_close(self):
self.__delete_after()
self.__model.exit()
self.__view.destroy_window(self.__key)
def on_message_user_button_click(self, event=None):
window = self.__view.get_window(self.__key)[0]
selection_friends = window.middle_frame.friends_list.curselection()
selection_found_user = window.left_frame.found_user_list.curselection()
if selection_friends:
username = window.middle_frame.friends_list.get(
window.middle_frame.friends_list.curselection()
)
key = "message_window_" + username
if self.__view.window_exists(key):
action = self.__view.get_window(key)[1]
action.focus_window()
else:
action = message_window_actions.MessageWindowActions(
self.__model,
self.__view
)
window = message_window.MessageWindow(action)
action.on_message_window(key, window, username)
if selection_found_user:
username = window.left_frame.found_user_list.get(
window.left_frame.found_user_list.curselection()
)
key = "message_window_" + username
if self.__view.window_exists(key):
action = self.__view.get_window(key)[1]
action.focus_window()
else:
action = message_window_actions.MessageWindowActions(
self.__model,
self.__view
)
window = message_window.MessageWindow(action)
action.on_message_window(key, window, username)
def on_delete_user_button_click(self, event=None):
window = self.__view.get_window(self.__key)[0]
selection = window.middle_frame.friends_list.curselection()
if selection:
username = window.middle_frame.friends_list.get(
window.middle_frame.friends_list.curselection()
)
self.__model.delete_friend(username)
window.middle_frame.friends_list.delete(selection)
def __delete_after(self):
window = self.__view.get_window(self.__key)[0]
for after_id in self.after_id_list:
window.after_cancel(after_id)
def focus_window(self):
window = self.__view.get_window(self.__key)[0]
window.lift()
window.focus_force()
|
# Copyright 2018-2020 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Unit tests for the :mod:`pennylane.drawer.representation_resolver` module.
"""
from unittest.mock import Mock
import pytest
import numpy as np
import pennylane as qml
from pennylane.drawer.representation_resolver import RepresentationResolver
from pennylane.measure import state
@pytest.fixture
def unicode_representation_resolver():
"""An instance of a RepresentationResolver with unicode charset."""
return RepresentationResolver()
@pytest.fixture
def ascii_representation_resolver():
"""An instance of a RepresentationResolver with unicode charset."""
return RepresentationResolver(charset=qml.drawer.charsets.AsciiCharSet)
def two_wire_quantum_tape():
"""An instance of a QuantumTape to be used as operation in a circuit."""
with qml.tape.QuantumTape() as quantum_tape:
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return quantum_tape
class TestRepresentationResolver:
"""Test the RepresentationResolver class."""
@pytest.mark.parametrize(
"list,element,index,list_after",
[
([1, 2, 3], 2, 1, [1, 2, 3]),
([1, 2, 2, 3], 2, 1, [1, 2, 2, 3]),
([1, 2, 3], 4, 3, [1, 2, 3, 4]),
],
)
def test_index_of_array_or_append(self, list, element, index, list_after):
"""Test the method index_of_array_or_append."""
assert RepresentationResolver.index_of_array_or_append(element, list) == index
assert list == list_after
@pytest.mark.parametrize(
"par,expected",
[
(3, "3"),
(5.236422, "5.24"),
],
)
def test_single_parameter_representation(self, unicode_representation_resolver, par, expected):
"""Test that single parameters are properly resolved."""
assert unicode_representation_resolver.single_parameter_representation(par) == expected
@pytest.mark.parametrize(
"op,wire,target",
[
(qml.PauliX(wires=[1]), 1, "X"),
(qml.CNOT(wires=[0, 1]), 1, "X"),
(qml.CNOT(wires=[0, 1]), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]), 1, "X"),
(qml.Toffoli(wires=[0, 2, 1]), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]), 2, "C"),
(qml.CSWAP(wires=[0, 2, 1]), 1, "SWAP"),
(qml.CSWAP(wires=[0, 2, 1]), 2, "SWAP"),
(qml.CSWAP(wires=[0, 2, 1]), 0, "C"),
(qml.PauliY(wires=[1]), 1, "Y"),
(qml.PauliZ(wires=[1]), 1, "Z"),
(qml.CZ(wires=[0, 1]), 1, "Z"),
(qml.CZ(wires=[0, 1]), 0, "C"),
(qml.Identity(wires=[1]), 1, "I"),
(qml.Hadamard(wires=[1]), 1, "H"),
(qml.PauliRot(3.14, "XX", wires=[0, 1]), 1, "RX(3.14)"),
(qml.PauliRot(3.14, "YZ", wires=[0, 1]), 1, "RZ(3.14)"),
(qml.PauliRot(3.14, "IXYZI", wires=[0, 1, 2, 3, 4]), 0, "RI(3.14)"),
(qml.PauliRot(3.14, "IXYZI", wires=[0, 1, 2, 3, 4]), 1, "RX(3.14)"),
(qml.PauliRot(3.14, "IXYZI", wires=[0, 1, 2, 3, 4]), 2, "RY(3.14)"),
(qml.PauliRot(3.14, "IXYZI", wires=[0, 1, 2, 3, 4]), 3, "RZ(3.14)"),
(qml.PauliRot(3.14, "IXYZI", wires=[0, 1, 2, 3, 4]), 4, "RI(3.14)"),
(qml.MultiRZ(3.14, wires=[0, 1]), 0, "RZ(3.14)"),
(qml.MultiRZ(3.14, wires=[0, 1]), 1, "RZ(3.14)"),
(qml.CRX(3.14, wires=[0, 1]), 1, "RX(3.14)"),
(qml.CRX(3.14, wires=[0, 1]), 0, "C"),
(qml.CRY(3.14, wires=[0, 1]), 1, "RY(3.14)"),
(qml.CRY(3.14, wires=[0, 1]), 0, "C"),
(qml.CRZ(3.14, wires=[0, 1]), 1, "RZ(3.14)"),
(qml.CRZ(3.14, wires=[0, 1]), 0, "C"),
(qml.CRot(3.14, 2.14, 1.14, wires=[0, 1]), 1, "Rot(3.14, 2.14, 1.14)"),
(qml.CRot(3.14, 2.14, 1.14, wires=[0, 1]), 0, "C"),
(qml.PhaseShift(3.14, wires=[0]), 0, "Rϕ(3.14)"),
(qml.Beamsplitter(1, 2, wires=[0, 1]), 1, "BS(1, 2)"),
(qml.Beamsplitter(1, 2, wires=[0, 1]), 0, "BS(1, 2)"),
(qml.Squeezing(1, 2, wires=[1]), 1, "S(1, 2)"),
(qml.TwoModeSqueezing(1, 2, wires=[0, 1]), 1, "S(1, 2)"),
(qml.TwoModeSqueezing(1, 2, wires=[0, 1]), 0, "S(1, 2)"),
(qml.Displacement(1, 2, wires=[1]), 1, "D(1, 2)"),
(qml.NumberOperator(wires=[1]), 1, "n"),
(qml.Rotation(3.14, wires=[1]), 1, "R(3.14)"),
(qml.ControlledAddition(3.14, wires=[0, 1]), 1, "X(3.14)"),
(qml.ControlledAddition(3.14, wires=[0, 1]), 0, "C"),
(qml.ControlledPhase(3.14, wires=[0, 1]), 1, "Z(3.14)"),
(qml.ControlledPhase(3.14, wires=[0, 1]), 0, "C"),
(qml.ThermalState(3, wires=[1]), 1, "Thermal(3)"),
(
qml.GaussianState(np.array([[2, 0], [0, 2]]), np.array([1, 2]), wires=[1]),
1,
"Gaussian(M0,M1)",
),
(qml.QuadraticPhase(3.14, wires=[1]), 1, "P(3.14)"),
(qml.RX(3.14, wires=[1]), 1, "RX(3.14)"),
(qml.S(wires=[2]), 2, "S"),
(qml.T(wires=[2]), 2, "T"),
(qml.RX(3.14, wires=[1]), 1, "RX(3.14)"),
(qml.RY(3.14, wires=[1]), 1, "RY(3.14)"),
(qml.RZ(3.14, wires=[1]), 1, "RZ(3.14)"),
(qml.Rot(3.14, 2.14, 1.14, wires=[1]), 1, "Rot(3.14, 2.14, 1.14)"),
(qml.U1(3.14, wires=[1]), 1, "U1(3.14)"),
(qml.U2(3.14, 2.14, wires=[1]), 1, "U2(3.14, 2.14)"),
(qml.U3(3.14, 2.14, 1.14, wires=[1]), 1, "U3(3.14, 2.14, 1.14)"),
(qml.BasisState(np.array([0, 1, 0]), wires=[1, 2, 3]), 1, "|0⟩"),
(qml.BasisState(np.array([0, 1, 0]), wires=[1, 2, 3]), 2, "|1⟩"),
(qml.BasisState(np.array([0, 1, 0]), wires=[1, 2, 3]), 3, "|0⟩"),
(qml.QubitStateVector(np.array([0, 1, 0, 0]), wires=[1, 2]), 1, "QubitStateVector(M0)"),
(qml.QubitStateVector(np.array([0, 1, 0, 0]), wires=[1, 2]), 2, "QubitStateVector(M0)"),
(qml.QubitUnitary(np.eye(2), wires=[1]), 1, "U0"),
(qml.QubitUnitary(np.eye(4), wires=[1, 2]), 2, "U0"),
(qml.Kerr(3.14, wires=[1]), 1, "Kerr(3.14)"),
(qml.CrossKerr(3.14, wires=[1, 2]), 1, "CrossKerr(3.14)"),
(qml.CrossKerr(3.14, wires=[1, 2]), 2, "CrossKerr(3.14)"),
(qml.CubicPhase(3.14, wires=[1]), 1, "V(3.14)"),
(qml.InterferometerUnitary(np.eye(4), wires=[1, 3]), 1, "InterferometerUnitary(M0)"),
(qml.InterferometerUnitary(np.eye(4), wires=[1, 3]), 3, "InterferometerUnitary(M0)"),
(qml.CatState(3.14, 2.14, 1, wires=[1]), 1, "CatState(3.14, 2.14, 1)"),
(qml.CoherentState(3.14, 2.14, wires=[1]), 1, "CoherentState(3.14, 2.14)"),
(
qml.FockDensityMatrix(np.kron(np.eye(4), np.eye(4)), wires=[1, 2]),
1,
"FockDensityMatrix(M0)",
),
(
qml.FockDensityMatrix(np.kron(np.eye(4), np.eye(4)), wires=[1, 2]),
2,
"FockDensityMatrix(M0)",
),
(
qml.DisplacedSqueezedState(3.14, 2.14, 1.14, 0.14, wires=[1]),
1,
"DisplacedSqueezedState(3.14, 2.14, 1.14, 0.14)",
),
(qml.FockState(7, wires=[1]), 1, "|7⟩"),
(qml.FockStateVector(np.array([4, 5, 7]), wires=[1, 2, 3]), 1, "|4⟩"),
(qml.FockStateVector(np.array([4, 5, 7]), wires=[1, 2, 3]), 2, "|5⟩"),
(qml.FockStateVector(np.array([4, 5, 7]), wires=[1, 2, 3]), 3, "|7⟩"),
(qml.SqueezedState(3.14, 2.14, wires=[1]), 1, "SqueezedState(3.14, 2.14)"),
(qml.Hermitian(np.eye(4), wires=[1, 2]), 1, "H0"),
(qml.Hermitian(np.eye(4), wires=[1, 2]), 2, "H0"),
(qml.X(wires=[1]), 1, "x"),
(qml.P(wires=[1]), 1, "p"),
(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]), 1, "|4,5,7╳4,5,7|"),
(
qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1]),
2,
"1+2x₀-1.3x₁+6p₁",
),
(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
),
1,
"1.2+1.1x₀+3.2p₀+1.2x₀²+2.3p₀²+3x₀p₀",
),
(
qml.PolyXP(
np.array(
[
[1.2, 2.3, 4.5, 0, 0],
[-1.2, 1.2, -1.5, 0, 0],
[-1.3, 4.5, 2.3, 0, 0],
[0, 2.6, 0, 0, 0],
[0, 0, 0, -4.7, -1.0],
]
),
wires=[1],
),
1,
"1.2+1.1x₀+3.2p₀+1.2x₀²+2.3p₀²+3x₀p₀+2.6x₀x₁-p₁²-4.7x₁p₁",
),
(qml.QuadOperator(3.14, wires=[1]), 1, "cos(3.14)x+sin(3.14)p"),
(qml.PauliX(wires=[1]).inv(), 1, "X⁻¹"),
(qml.CNOT(wires=[0, 1]).inv(), 1, "X⁻¹"),
(qml.CNOT(wires=[0, 1]).inv(), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]).inv(), 1, "X⁻¹"),
(qml.Toffoli(wires=[0, 2, 1]).inv(), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]).inv(), 2, "C"),
(qml.measure.sample(wires=[0, 1]), 0, "basis"), # not providing an observable in
(qml.measure.sample(wires=[0, 1]), 1, "basis"), # sample gets displayed as raw
(two_wire_quantum_tape(), 0, "QuantumTape:T0"),
(two_wire_quantum_tape(), 1, "QuantumTape:T0"),
],
)
def test_operator_representation_unicode(
self, unicode_representation_resolver, op, wire, target
):
"""Test that an Operator instance is properly resolved."""
assert unicode_representation_resolver.operator_representation(op, wire) == target
@pytest.mark.parametrize(
"op,wire,target",
[
(qml.PauliX(wires=[1]), 1, "X"),
(qml.CNOT(wires=[0, 1]), 1, "X"),
(qml.CNOT(wires=[0, 1]), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]), 1, "X"),
(qml.Toffoli(wires=[0, 2, 1]), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]), 2, "C"),
(qml.CSWAP(wires=[0, 2, 1]), 1, "SWAP"),
(qml.CSWAP(wires=[0, 2, 1]), 2, "SWAP"),
(qml.CSWAP(wires=[0, 2, 1]), 0, "C"),
(qml.PauliY(wires=[1]), 1, "Y"),
(qml.PauliZ(wires=[1]), 1, "Z"),
(qml.CZ(wires=[0, 1]), 1, "Z"),
(qml.CZ(wires=[0, 1]), 0, "C"),
(qml.Identity(wires=[1]), 1, "I"),
(qml.Hadamard(wires=[1]), 1, "H"),
(qml.CRX(3.14, wires=[0, 1]), 1, "RX(3.14)"),
(qml.CRX(3.14, wires=[0, 1]), 0, "C"),
(qml.CRY(3.14, wires=[0, 1]), 1, "RY(3.14)"),
(qml.CRY(3.14, wires=[0, 1]), 0, "C"),
(qml.CRZ(3.14, wires=[0, 1]), 1, "RZ(3.14)"),
(qml.CRZ(3.14, wires=[0, 1]), 0, "C"),
(qml.CRot(3.14, 2.14, 1.14, wires=[0, 1]), 1, "Rot(3.14, 2.14, 1.14)"),
(qml.CRot(3.14, 2.14, 1.14, wires=[0, 1]), 0, "C"),
(qml.PhaseShift(3.14, wires=[0]), 0, "Rϕ(3.14)"),
(qml.Beamsplitter(1, 2, wires=[0, 1]), 1, "BS(1, 2)"),
(qml.Beamsplitter(1, 2, wires=[0, 1]), 0, "BS(1, 2)"),
(qml.Squeezing(1, 2, wires=[1]), 1, "S(1, 2)"),
(qml.TwoModeSqueezing(1, 2, wires=[0, 1]), 1, "S(1, 2)"),
(qml.TwoModeSqueezing(1, 2, wires=[0, 1]), 0, "S(1, 2)"),
(qml.Displacement(1, 2, wires=[1]), 1, "D(1, 2)"),
(qml.NumberOperator(wires=[1]), 1, "n"),
(qml.Rotation(3.14, wires=[1]), 1, "R(3.14)"),
(qml.ControlledAddition(3.14, wires=[0, 1]), 1, "X(3.14)"),
(qml.ControlledAddition(3.14, wires=[0, 1]), 0, "C"),
(qml.ControlledPhase(3.14, wires=[0, 1]), 1, "Z(3.14)"),
(qml.ControlledPhase(3.14, wires=[0, 1]), 0, "C"),
(qml.ThermalState(3, wires=[1]), 1, "Thermal(3)"),
(
qml.GaussianState(np.array([[2, 0], [0, 2]]), np.array([1, 2]), wires=[1]),
1,
"Gaussian(M0,M1)",
),
(qml.QuadraticPhase(3.14, wires=[1]), 1, "P(3.14)"),
(qml.RX(3.14, wires=[1]), 1, "RX(3.14)"),
(qml.S(wires=[2]), 2, "S"),
(qml.T(wires=[2]), 2, "T"),
(qml.RX(3.14, wires=[1]), 1, "RX(3.14)"),
(qml.RY(3.14, wires=[1]), 1, "RY(3.14)"),
(qml.RZ(3.14, wires=[1]), 1, "RZ(3.14)"),
(qml.Rot(3.14, 2.14, 1.14, wires=[1]), 1, "Rot(3.14, 2.14, 1.14)"),
(qml.U1(3.14, wires=[1]), 1, "U1(3.14)"),
(qml.U2(3.14, 2.14, wires=[1]), 1, "U2(3.14, 2.14)"),
(qml.U3(3.14, 2.14, 1.14, wires=[1]), 1, "U3(3.14, 2.14, 1.14)"),
(qml.BasisState(np.array([0, 1, 0]), wires=[1, 2, 3]), 1, "|0>"),
(qml.BasisState(np.array([0, 1, 0]), wires=[1, 2, 3]), 2, "|1>"),
(qml.BasisState(np.array([0, 1, 0]), wires=[1, 2, 3]), 3, "|0>"),
(qml.QubitStateVector(np.array([0, 1, 0, 0]), wires=[1, 2]), 1, "QubitStateVector(M0)"),
(qml.QubitStateVector(np.array([0, 1, 0, 0]), wires=[1, 2]), 2, "QubitStateVector(M0)"),
(qml.QubitUnitary(np.eye(2), wires=[1]), 1, "U0"),
(qml.QubitUnitary(np.eye(4), wires=[1, 2]), 2, "U0"),
(qml.Kerr(3.14, wires=[1]), 1, "Kerr(3.14)"),
(qml.CrossKerr(3.14, wires=[1, 2]), 1, "CrossKerr(3.14)"),
(qml.CrossKerr(3.14, wires=[1, 2]), 2, "CrossKerr(3.14)"),
(qml.CubicPhase(3.14, wires=[1]), 1, "V(3.14)"),
(qml.InterferometerUnitary(np.eye(4), wires=[1, 3]), 1, "InterferometerUnitary(M0)"),
(qml.InterferometerUnitary(np.eye(4), wires=[1, 3]), 3, "InterferometerUnitary(M0)"),
(qml.CatState(3.14, 2.14, 1, wires=[1]), 1, "CatState(3.14, 2.14, 1)"),
(qml.CoherentState(3.14, 2.14, wires=[1]), 1, "CoherentState(3.14, 2.14)"),
(
qml.FockDensityMatrix(np.kron(np.eye(4), np.eye(4)), wires=[1, 2]),
1,
"FockDensityMatrix(M0)",
),
(
qml.FockDensityMatrix(np.kron(np.eye(4), np.eye(4)), wires=[1, 2]),
2,
"FockDensityMatrix(M0)",
),
(
qml.DisplacedSqueezedState(3.14, 2.14, 1.14, 0.14, wires=[1]),
1,
"DisplacedSqueezedState(3.14, 2.14, 1.14, 0.14)",
),
(qml.FockState(7, wires=[1]), 1, "|7>"),
(qml.FockStateVector(np.array([4, 5, 7]), wires=[1, 2, 3]), 1, "|4>"),
(qml.FockStateVector(np.array([4, 5, 7]), wires=[1, 2, 3]), 2, "|5>"),
(qml.FockStateVector(np.array([4, 5, 7]), wires=[1, 2, 3]), 3, "|7>"),
(qml.SqueezedState(3.14, 2.14, wires=[1]), 1, "SqueezedState(3.14, 2.14)"),
(qml.Hermitian(np.eye(4), wires=[1, 2]), 1, "H0"),
(qml.Hermitian(np.eye(4), wires=[1, 2]), 2, "H0"),
(qml.X(wires=[1]), 1, "x"),
(qml.P(wires=[1]), 1, "p"),
(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]), 1, "|4,5,7X4,5,7|"),
(
qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1]),
2,
"1+2x_0-1.3x_1+6p_1",
),
(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
),
1,
"1.2+1.1x_0+3.2p_0+1.2x_0^2+2.3p_0^2+3x_0p_0",
),
(
qml.PolyXP(
np.array(
[
[1.2, 2.3, 4.5, 0, 0],
[-1.2, 1.2, -1.5, 0, 0],
[-1.3, 4.5, 2.3, 0, 0],
[0, 2.6, 0, 0, 0],
[0, 0, 0, -4.7, 0],
]
),
wires=[1],
),
1,
"1.2+1.1x_0+3.2p_0+1.2x_0^2+2.3p_0^2+3x_0p_0+2.6x_0x_1-4.7x_1p_1",
),
(qml.QuadOperator(3.14, wires=[1]), 1, "cos(3.14)x+sin(3.14)p"),
(qml.QuadOperator(3.14, wires=[1]), 1, "cos(3.14)x+sin(3.14)p"),
(qml.PauliX(wires=[1]).inv(), 1, "X^-1"),
(qml.CNOT(wires=[0, 1]).inv(), 1, "X^-1"),
(qml.CNOT(wires=[0, 1]).inv(), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]).inv(), 1, "X^-1"),
(qml.Toffoli(wires=[0, 2, 1]).inv(), 0, "C"),
(qml.Toffoli(wires=[0, 2, 1]).inv(), 2, "C"),
(qml.measure.sample(wires=[0, 1]), 0, "basis"), # not providing an observable in
(qml.measure.sample(wires=[0, 1]), 1, "basis"), # sample gets displayed as raw
(two_wire_quantum_tape(), 0, "QuantumTape:T0"),
(two_wire_quantum_tape(), 1, "QuantumTape:T0"),
],
)
def test_operator_representation_ascii(self, ascii_representation_resolver, op, wire, target):
"""Test that an Operator instance is properly resolved."""
assert ascii_representation_resolver.operator_representation(op, wire) == target
@pytest.mark.parametrize(
"obs,wire,target",
[
(qml.expval(qml.PauliX(wires=[1])), 1, "⟨X⟩"),
(qml.expval(qml.PauliY(wires=[1])), 1, "⟨Y⟩"),
(qml.expval(qml.PauliZ(wires=[1])), 1, "⟨Z⟩"),
(qml.expval(qml.Hadamard(wires=[1])), 1, "⟨H⟩"),
(qml.expval(qml.Hermitian(np.eye(4), wires=[1, 2])), 1, "⟨H0⟩"),
(qml.expval(qml.Hermitian(np.eye(4), wires=[1, 2])), 2, "⟨H0⟩"),
(qml.expval(qml.NumberOperator(wires=[1])), 1, "⟨n⟩"),
(qml.expval(qml.X(wires=[1])), 1, "⟨x⟩"),
(qml.expval(qml.P(wires=[1])), 1, "⟨p⟩"),
(
qml.expval(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3])),
1,
"⟨|4,5,7╳4,5,7|⟩",
),
(
qml.expval(qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1])),
2,
"⟨1+2x₀-1.3x₁+6p₁⟩",
),
(
qml.expval(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
)
),
1,
"⟨1.2+1.1x₀+3.2p₀+1.2x₀²+2.3p₀²+3x₀p₀⟩",
),
(qml.expval(qml.QuadOperator(3.14, wires=[1])), 1, "⟨cos(3.14)x+sin(3.14)p⟩"),
(qml.var(qml.PauliX(wires=[1])), 1, "Var[X]"),
(qml.var(qml.PauliY(wires=[1])), 1, "Var[Y]"),
(qml.var(qml.PauliZ(wires=[1])), 1, "Var[Z]"),
(qml.var(qml.Hadamard(wires=[1])), 1, "Var[H]"),
(qml.var(qml.Hermitian(np.eye(4), wires=[1, 2])), 1, "Var[H0]"),
(qml.var(qml.Hermitian(np.eye(4), wires=[1, 2])), 2, "Var[H0]"),
(qml.var(qml.NumberOperator(wires=[1])), 1, "Var[n]"),
(qml.var(qml.X(wires=[1])), 1, "Var[x]"),
(qml.var(qml.P(wires=[1])), 1, "Var[p]"),
(
qml.var(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3])),
1,
"Var[|4,5,7╳4,5,7|]",
),
(
qml.var(qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1])),
2,
"Var[1+2x₀-1.3x₁+6p₁]",
),
(
qml.var(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
)
),
1,
"Var[1.2+1.1x₀+3.2p₀+1.2x₀²+2.3p₀²+3x₀p₀]",
),
(qml.var(qml.QuadOperator(3.14, wires=[1])), 1, "Var[cos(3.14)x+sin(3.14)p]"),
(qml.sample(qml.PauliX(wires=[1])), 1, "Sample[X]"),
(qml.sample(qml.PauliY(wires=[1])), 1, "Sample[Y]"),
(qml.sample(qml.PauliZ(wires=[1])), 1, "Sample[Z]"),
(qml.sample(qml.Hadamard(wires=[1])), 1, "Sample[H]"),
(qml.sample(qml.Hermitian(np.eye(4), wires=[1, 2])), 1, "Sample[H0]"),
(qml.sample(qml.Hermitian(np.eye(4), wires=[1, 2])), 2, "Sample[H0]"),
(qml.sample(qml.NumberOperator(wires=[1])), 1, "Sample[n]"),
(qml.sample(qml.X(wires=[1])), 1, "Sample[x]"),
(qml.sample(qml.P(wires=[1])), 1, "Sample[p]"),
(
qml.sample(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3])),
1,
"Sample[|4,5,7╳4,5,7|]",
),
(
qml.sample(qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1])),
2,
"Sample[1+2x₀-1.3x₁+6p₁]",
),
(
qml.sample(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
)
),
1,
"Sample[1.2+1.1x₀+3.2p₀+1.2x₀²+2.3p₀²+3x₀p₀]",
),
(qml.sample(qml.QuadOperator(3.14, wires=[1])), 1, "Sample[cos(3.14)x+sin(3.14)p]"),
(
qml.expval(qml.PauliX(wires=[1]) @ qml.PauliY(wires=[2]) @ qml.PauliZ(wires=[3])),
1,
"⟨X ⊗ Y ⊗ Z⟩",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
1,
"⟨|4,5,7╳4,5,7| ⊗ x⟩",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
2,
"⟨|4,5,7╳4,5,7| ⊗ x⟩",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
3,
"⟨|4,5,7╳4,5,7| ⊗ x⟩",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
4,
"⟨|4,5,7╳4,5,7| ⊗ x⟩",
),
(
qml.sample(
qml.Hermitian(np.eye(4), wires=[1, 2]) @ qml.Hermitian(np.eye(4), wires=[0, 3])
),
0,
"Sample[H0 ⊗ H0]",
),
(
qml.sample(
qml.Hermitian(np.eye(4), wires=[1, 2])
@ qml.Hermitian(2 * np.eye(4), wires=[0, 3])
),
0,
"Sample[H0 ⊗ H1]",
),
(qml.probs([0]), 0, "Probs"),
(state(), 0, "State"),
],
)
def test_output_representation_unicode(
self, unicode_representation_resolver, obs, wire, target
):
"""Test that an Observable instance with return type is properly resolved."""
assert unicode_representation_resolver.output_representation(obs, wire) == target
def test_fallback_output_representation_unicode(self, unicode_representation_resolver):
"""Test that an Observable instance with return type is properly resolved."""
obs = qml.PauliZ(0)
obs.return_type = "TestReturnType"
assert unicode_representation_resolver.output_representation(obs, 0) == "TestReturnType[Z]"
@pytest.mark.parametrize(
"obs,wire,target",
[
(qml.expval(qml.PauliX(wires=[1])), 1, "<X>"),
(qml.expval(qml.PauliY(wires=[1])), 1, "<Y>"),
(qml.expval(qml.PauliZ(wires=[1])), 1, "<Z>"),
(qml.expval(qml.Hadamard(wires=[1])), 1, "<H>"),
(qml.expval(qml.Hermitian(np.eye(4), wires=[1, 2])), 1, "<H0>"),
(qml.expval(qml.Hermitian(np.eye(4), wires=[1, 2])), 2, "<H0>"),
(qml.expval(qml.NumberOperator(wires=[1])), 1, "<n>"),
(qml.expval(qml.X(wires=[1])), 1, "<x>"),
(qml.expval(qml.P(wires=[1])), 1, "<p>"),
(
qml.expval(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3])),
1,
"<|4,5,7X4,5,7|>",
),
(
qml.expval(qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1])),
2,
"<1+2x_0-1.3x_1+6p_1>",
),
(
qml.expval(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
)
),
1,
"<1.2+1.1x_0+3.2p_0+1.2x_0^2+2.3p_0^2+3x_0p_0>",
),
(qml.expval(qml.QuadOperator(3.14, wires=[1])), 1, "<cos(3.14)x+sin(3.14)p>"),
(qml.var(qml.PauliX(wires=[1])), 1, "Var[X]"),
(qml.var(qml.PauliY(wires=[1])), 1, "Var[Y]"),
(qml.var(qml.PauliZ(wires=[1])), 1, "Var[Z]"),
(qml.var(qml.Hadamard(wires=[1])), 1, "Var[H]"),
(qml.var(qml.Hermitian(np.eye(4), wires=[1, 2])), 1, "Var[H0]"),
(qml.var(qml.Hermitian(np.eye(4), wires=[1, 2])), 2, "Var[H0]"),
(qml.var(qml.NumberOperator(wires=[1])), 1, "Var[n]"),
(qml.var(qml.X(wires=[1])), 1, "Var[x]"),
(qml.var(qml.P(wires=[1])), 1, "Var[p]"),
(
qml.var(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3])),
1,
"Var[|4,5,7X4,5,7|]",
),
(
qml.var(qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1])),
2,
"Var[1+2x_0-1.3x_1+6p_1]",
),
(
qml.var(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
)
),
1,
"Var[1.2+1.1x_0+3.2p_0+1.2x_0^2+2.3p_0^2+3x_0p_0]",
),
(qml.var(qml.QuadOperator(3.14, wires=[1])), 1, "Var[cos(3.14)x+sin(3.14)p]"),
(qml.sample(qml.PauliX(wires=[1])), 1, "Sample[X]"),
(qml.sample(qml.PauliY(wires=[1])), 1, "Sample[Y]"),
(qml.sample(qml.PauliZ(wires=[1])), 1, "Sample[Z]"),
(qml.sample(qml.Hadamard(wires=[1])), 1, "Sample[H]"),
(qml.sample(qml.Hermitian(np.eye(4), wires=[1, 2])), 1, "Sample[H0]"),
(qml.sample(qml.Hermitian(np.eye(4), wires=[1, 2])), 2, "Sample[H0]"),
(qml.sample(qml.NumberOperator(wires=[1])), 1, "Sample[n]"),
(qml.sample(qml.X(wires=[1])), 1, "Sample[x]"),
(qml.sample(qml.P(wires=[1])), 1, "Sample[p]"),
(
qml.sample(qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3])),
1,
"Sample[|4,5,7X4,5,7|]",
),
(
qml.sample(qml.PolyXP(np.array([1, 2, 0, -1.3, 6]), wires=[1])),
2,
"Sample[1+2x_0-1.3x_1+6p_1]",
),
(
qml.sample(
qml.PolyXP(
np.array([[1.2, 2.3, 4.5], [-1.2, 1.2, -1.5], [-1.3, 4.5, 2.3]]), wires=[1]
)
),
1,
"Sample[1.2+1.1x_0+3.2p_0+1.2x_0^2+2.3p_0^2+3x_0p_0]",
),
(qml.sample(qml.QuadOperator(3.14, wires=[1])), 1, "Sample[cos(3.14)x+sin(3.14)p]"),
(
qml.expval(qml.PauliX(wires=[1]) @ qml.PauliY(wires=[2]) @ qml.PauliZ(wires=[3])),
1,
"<X @ Y @ Z>",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
1,
"<|4,5,7X4,5,7| @ x>",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
2,
"<|4,5,7X4,5,7| @ x>",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
3,
"<|4,5,7X4,5,7| @ x>",
),
(
qml.expval(
qml.FockStateProjector(np.array([4, 5, 7]), wires=[1, 2, 3]) @ qml.X(wires=[4])
),
4,
"<|4,5,7X4,5,7| @ x>",
),
(
qml.sample(
qml.Hermitian(np.eye(4), wires=[1, 2]) @ qml.Hermitian(np.eye(4), wires=[0, 3])
),
0,
"Sample[H0 @ H0]",
),
(
qml.sample(
qml.Hermitian(np.eye(4), wires=[1, 2])
@ qml.Hermitian(2 * np.eye(4), wires=[0, 3])
),
0,
"Sample[H0 @ H1]",
),
(qml.probs([0]), 0, "Probs"),
(state(), 0, "State"),
],
)
def test_output_representation_ascii(self, ascii_representation_resolver, obs, wire, target):
"""Test that an Observable instance with return type is properly resolved."""
assert ascii_representation_resolver.output_representation(obs, wire) == target
def test_element_representation_none(self, unicode_representation_resolver):
"""Test that element_representation properly handles None."""
assert unicode_representation_resolver.element_representation(None, 0) == ""
def test_element_representation_str(self, unicode_representation_resolver):
"""Test that element_representation properly handles strings."""
assert unicode_representation_resolver.element_representation("Test", 0) == "Test"
def test_element_representation_calls_output(self, unicode_representation_resolver):
"""Test that element_representation calls output_representation for returned observables."""
unicode_representation_resolver.output_representation = Mock()
obs = qml.sample(qml.PauliX(3))
wire = 3
unicode_representation_resolver.element_representation(obs, wire)
assert unicode_representation_resolver.output_representation.call_args[0] == (obs, wire)
def test_element_representation_calls_operator(self, unicode_representation_resolver):
"""Test that element_representation calls operator_representation for all operators that are not returned."""
unicode_representation_resolver.operator_representation = Mock()
op = qml.PauliX(3)
wire = 3
unicode_representation_resolver.element_representation(op, wire)
assert unicode_representation_resolver.operator_representation.call_args[0] == (op, wire)
|
#include<stdio.h>
void main ()
{
char *p = "hello Vishwas";
printf("String p: %s\n",p);
char *q;
printf("copying the content of p into q...\n");
q = p;
printf("String q: %s\n",q);
}
|
const { createDecorateReactTopJSXVisitor, default: createDecorateReactVisitor } = require('../../../src')
const nps = require('path')
module.exports = (babel) => {
return {
visitor: {
Program(path) {
const run1 = createDecorateReactVisitor({
prefix: 'decorate',
decorateLibPath: require.resolve('./react'),
detectFunctionComponent: false,
moduleInteropPath: null,
importType: 'default',
transformData: (data, path1, babelPluginPass, helper) => {
return nps.relative(__dirname, babelPluginPass.filename)
},
visitorTypes: []
})
const run2 = createDecorateReactTopJSXVisitor({
prefix: 'decorate',
visitorTypes: [],
decorateLibPath: require.resolve('./jsx'),
moduleInteropPath: null,
detectClassComponent: false,
importType: 'default',
transformData: (data, path1, babelPluginPass, helper) => {
return nps.relative(__dirname, babelPluginPass.filename)
}
})
run1.Program.call(this, path)
run2.Program.call(this, path)
}
}
}
}
|
/** File: candy.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global jQuery */
/** Class: Candy
* Candy base class for initalizing the view and the core
*
* Parameters:
* (Candy) self - itself
* (jQuery) $ - jQuery
*/
var Candy = function(self, $) {
/** Object: about
* About candy
*
* Contains:
* (String) name - Candy
* (Float) version - Candy version
*/
self.about = {
name: "Candy",
version: "2.2.0"
};
/** Function: init
* Init view & core
*
* Parameters:
* (String) service - URL to the BOSH interface
* (Object) options - Options for candy
*
* Options:
* (Boolean) debug - Debug (Default: false)
* (Array|Boolean) autojoin - Autojoin these channels. When boolean true, do not autojoin, wait if the server sends something.
*/
self.init = function(service, options) {
if (!options.viewClass) {
options.viewClass = self.View;
}
options.viewClass.init($("#candy"), options.view);
self.Core.init(service, options.core);
};
return self;
}(Candy || {}, jQuery);
/** File: core.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, window, Strophe, jQuery */
/** Class: Candy.Core
* Candy Chat Core
*
* Parameters:
* (Candy.Core) self - itself
* (Strophe) Strophe - Strophe JS
* (jQuery) $ - jQuery
*/
Candy.Core = function(self, Strophe, $) {
/** PrivateVariable: _connection
* Strophe connection
*/
var _connection = null, /** PrivateVariable: _service
* URL of BOSH service
*/
_service = null, /** PrivateVariable: _user
* Current user (me)
*/
_user = null, /** PrivateVariable: _roster
* Main roster of contacts
*/
_roster = null, /** PrivateVariable: _rooms
* Opened rooms, containing instances of Candy.Core.ChatRooms
*/
_rooms = {}, /** PrivateVariable: _anonymousConnection
* Set in <Candy.Core.connect> when jidOrHost doesn't contain a @-char.
*/
_anonymousConnection = false, /** PrivateVariable: _status
* Current Strophe connection state
*/
_status, /** PrivateVariable: _options
* Config options
*/
_options = {
/** Boolean: autojoin
* If set to `true` try to get the bookmarks and autojoin the rooms (supported by ejabberd, Openfire).
* You may want to define an array of rooms to autojoin: `['room1@conference.host.tld', 'room2...]` (ejabberd, Openfire, ...)
*/
autojoin: undefined,
/** Boolean: disconnectWithoutTabs
* If you set to `false`, when you close all of the tabs, the service does not disconnect.
* Set to `true`, when you close all of the tabs, the service will disconnect.
*/
disconnectWithoutTabs: true,
/** String: conferenceDomain
* Holds the prefix for an XMPP chat server's conference subdomain.
* If not set, assumes no specific subdomain.
*/
conferenceDomain: undefined,
/** Boolean: debug
* Enable debug
*/
debug: false,
/** List: domains
* If non-null, causes login form to offer this
* pre-set list of domains to choose between when
* logging in. Any user-provided domain is discarded
* and the selected domain is appended.
* For each list item, only characters up to the first
* whitespace are used, so you can append extra
* information to each item if desired.
*/
domains: null,
/** Boolean: hideDomainList
* If true, the domain list defined above is suppressed.
* Without a selector displayed, the default domain
* (usually the first one listed) will be used as
* described above. Probably only makes sense with a
* single domain defined.
*/
hideDomainList: false,
/** Boolean: disableCoreNotifications
* If set to `true`, the built-in notifications (sounds and badges) are disabled.
* This is useful if you are using a plugin to handle notifications.
*/
disableCoreNotifications: false,
/** Boolean: disableWindowUnload
* Disable window unload handler which usually disconnects from XMPP
*/
disableWindowUnload: false,
/** Integer: presencePriority
* Default priority for presence messages in order to receive messages across different resources
*/
presencePriority: 1,
/** String: resource
* JID resource to use when connecting to the server.
* Specify `''` (an empty string) to request a random resource.
*/
resource: Candy.about.name,
/** Boolean: useParticipantRealJid
* If set true, will direct one-on-one chats to participant's real JID rather than their MUC jid
*/
useParticipantRealJid: false,
/**
* Roster version we claim to already have. Used when loading a cached roster.
* Defaults to null, indicating we don't have the roster.
*/
initialRosterVersion: null,
/**
* Initial roster items. Loaded from a cache, used to bootstrap displaying a roster prior to fetching updates.
*/
initialRosterItems: []
}, /** PrivateFunction: _addNamespace
* Adds a namespace.
*
* Parameters:
* (String) name - namespace name (will become a constant living in Strophe.NS.*)
* (String) value - XML Namespace
*/
_addNamespace = function(name, value) {
Strophe.addNamespace(name, value);
}, /** PrivateFunction: _addNamespaces
* Adds namespaces needed by Candy.
*/
_addNamespaces = function() {
_addNamespace("PRIVATE", "jabber:iq:private");
_addNamespace("BOOKMARKS", "storage:bookmarks");
_addNamespace("PRIVACY", "jabber:iq:privacy");
_addNamespace("DELAY", "urn:xmpp:delay");
_addNamespace("JABBER_DELAY", "jabber:x:delay");
_addNamespace("PUBSUB", "http://jabber.org/protocol/pubsub");
_addNamespace("CARBONS", "urn:xmpp:carbons:2");
}, _getEscapedJidFromJid = function(jid) {
var node = Strophe.getNodeFromJid(jid), domain = Strophe.getDomainFromJid(jid);
return node ? Strophe.escapeNode(node) + "@" + domain : domain;
};
/** Function: init
* Initialize Core.
*
* Parameters:
* (String) service - URL of BOSH/Websocket service
* (Object) options - Options for candy
*/
self.init = function(service, options) {
_service = service;
// Apply options
$.extend(true, _options, options);
// Enable debug logging
if (_options.debug) {
if (typeof window.console !== undefined && typeof window.console.log !== undefined) {
// Strophe has a polyfill for bind which doesn't work in IE8.
if (Function.prototype.bind && Candy.Util.getIeVersion() > 8) {
self.log = Function.prototype.bind.call(console.log, console);
} else {
self.log = function() {
Function.prototype.apply.call(console.log, console, arguments);
};
}
}
Strophe.log = function(level, message) {
var level_name, console_level;
switch (level) {
case Strophe.LogLevel.DEBUG:
level_name = "DEBUG";
console_level = "log";
break;
case Strophe.LogLevel.INFO:
level_name = "INFO";
console_level = "info";
break;
case Strophe.LogLevel.WARN:
level_name = "WARN";
console_level = "info";
break;
case Strophe.LogLevel.ERROR:
level_name = "ERROR";
console_level = "error";
break;
case Strophe.LogLevel.FATAL:
level_name = "FATAL";
console_level = "error";
break;
}
console[console_level]("[Strophe][" + level_name + "]: " + message);
};
self.log("[Init] Debugging enabled");
}
_addNamespaces();
_roster = new Candy.Core.ChatRoster();
// Connect to BOSH/Websocket service
_connection = new Openfire.Connection(_service); // BAO
_connection.rawInput = self.rawInput.bind(self);
_connection.rawOutput = self.rawOutput.bind(self);
// set caps node
_connection.caps.node = "https://candy-chat.github.io/candy/";
// Window unload handler... works on all browsers but Opera. There is NO workaround.
// Opera clients getting disconnected 1-2 minutes delayed.
if (!_options.disableWindowUnload) {
window.onbeforeunload = self.onWindowUnload;
}
};
/** Function: registerEventHandlers
* Adds listening handlers to the connection.
*
* Use with caution from outside of Candy.
*/
self.registerEventHandlers = function() {
self.addHandler(self.Event.Jabber.Version, Strophe.NS.VERSION, "iq");
self.addHandler(self.Event.Jabber.Presence, null, "presence");
self.addHandler(self.Event.Jabber.Message, null, "message");
self.addHandler(self.Event.Jabber.Bookmarks, Strophe.NS.PRIVATE, "iq");
self.addHandler(self.Event.Jabber.Room.Disco, Strophe.NS.DISCO_INFO, "iq", "result");
self.addHandler(_connection.disco._onDiscoInfo.bind(_connection.disco), Strophe.NS.DISCO_INFO, "iq", "get");
self.addHandler(_connection.disco._onDiscoItems.bind(_connection.disco), Strophe.NS.DISCO_ITEMS, "iq", "get");
self.addHandler(_connection.caps._delegateCapabilities.bind(_connection.caps), Strophe.NS.CAPS);
};
/** Function: connect
* Connect to the jabber host.
*
* There are four different procedures to login:
* connect('JID', 'password') - Connect a registered user
* connect('domain') - Connect anonymously to the domain. The user should receive a random JID.
* connect('domain', null, 'nick') - Connect anonymously to the domain. The user should receive a random JID but with a nick set.
* connect('JID') - Show login form and prompt for password. JID input is hidden.
* connect() - Show login form and prompt for JID and password.
*
* See:
* <Candy.Core.attach()> for attaching an already established session.
*
* Parameters:
* (String) jidOrHost - JID or Host
* (String) password - Password of the user
* (String) nick - Nick of the user. Set one if you want to anonymously connect but preset a nick. If jidOrHost is a domain
* and this param is not set, Candy will prompt for a nick.
*/
self.connect = function(jidOrHost, password, nick) {
// Reset before every connection attempt to make sure reconnections work after authfail, alltabsclosed, ...
_connection.reset();
self.registerEventHandlers();
/** Event: candy:core.before-connect
* Triggered before a connection attempt is made.
*
* Plugins should register their stanza handlers using this event
* to ensure that they are set.
*
* See also <#84 at https://github.com/candy-chat/candy/issues/84>.
*
* Parameters:
* (Strophe.Connection) conncetion - Strophe connection
*/
$(Candy).triggerHandler("candy:core.before-connect", {
connection: _connection
});
_anonymousConnection = !_anonymousConnection ? jidOrHost && jidOrHost.indexOf("@") < 0 : true;
if (jidOrHost && password) {
// Respect the resource, if provided
var resource = Strophe.getResourceFromJid(jidOrHost);
if (resource) {
_options.resource = resource;
}
// authentication
_connection.connect(_getEscapedJidFromJid(jidOrHost) + "/" + _options.resource, password, Candy.Core.Event.Strophe.Connect);
if (nick) {
_user = new self.ChatUser(jidOrHost, nick);
} else {
_user = new self.ChatUser(jidOrHost, Strophe.getNodeFromJid(jidOrHost));
}
} else if (jidOrHost && nick) {
// anonymous connect
_connection.connect(_getEscapedJidFromJid(jidOrHost) + "/" + _options.resource, null, Candy.Core.Event.Strophe.Connect);
_user = new self.ChatUser(null, nick);
} else if (jidOrHost) {
Candy.Core.Event.Login(jidOrHost);
} else {
// display login modal
Candy.Core.Event.Login();
}
};
/** Function: attach
* Attach an already binded & connected session to the server
*
* _See_ Strophe.Connection.attach
*
* Parameters:
* (String) jid - Jabber ID
* (Integer) sid - Session ID
* (Integer) rid - rid
*/
self.attach = function(jid, sid, rid, nick) {
if (nick) {
_user = new self.ChatUser(jid, nick);
} else {
_user = new self.ChatUser(jid, Strophe.getNodeFromJid(jid));
}
// Reset before every connection attempt to make sure reconnections work after authfail, alltabsclosed, ...
_connection.reset();
self.registerEventHandlers();
_connection.attach(jid, sid, rid, Candy.Core.Event.Strophe.Connect);
};
/** Function: disconnect
* Leave all rooms and disconnect
*/
self.disconnect = function() {
if (_connection.connected) {
_connection.disconnect();
}
};
/** Function: addHandler
* Wrapper for Strophe.Connection.addHandler() to add a stanza handler for the connection.
*
* Parameters:
* (Function) handler - The user callback.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String) type - The stanza type attribute to match.
* (String) id - The stanza id attribute to match.
* (String) from - The stanza from attribute to match.
* (String) options - The handler options
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
self.addHandler = function(handler, ns, name, type, id, from, options) {
return _connection.addHandler(handler, ns, name, type, id, from, options);
};
/** Function: getRoster
* Gets main roster
*
* Returns:
* Instance of Candy.Core.ChatRoster
*/
self.getRoster = function() {
return _roster;
};
/** Function: getUser
* Gets current user
*
* Returns:
* Instance of Candy.Core.ChatUser
*/
self.getUser = function() {
return _user;
};
/** Function: setUser
* Set current user. Needed when anonymous login is used, as jid gets retrieved later.
*
* Parameters:
* (Candy.Core.ChatUser) user - User instance
*/
self.setUser = function(user) {
_user = user;
};
/** Function: getConnection
* Gets Strophe connection
*
* Returns:
* Instance of Strophe.Connection
*/
self.getConnection = function() {
return _connection;
};
/** Function: removeRoom
* Removes a room from the rooms list
*
* Parameters:
* (String) roomJid - roomJid
*/
self.removeRoom = function(roomJid) {
delete _rooms[roomJid];
};
/** Function: getRooms
* Gets all joined rooms
*
* Returns:
* Object containing instances of Candy.Core.ChatRoom
*/
self.getRooms = function() {
return _rooms;
};
/** Function: getStropheStatus
* Get the status set by Strophe.
*
* Returns:
* (Strophe.Status.*) - one of Strophe's statuses
*/
self.getStropheStatus = function() {
return _status;
};
/** Function: setStropheStatus
* Set the strophe status
*
* Called by:
* Candy.Core.Event.Strophe.Connect
*
* Parameters:
* (Strophe.Status.*) status - Strophe's status
*/
self.setStropheStatus = function(status) {
_status = status;
};
/** Function: isAnonymousConnection
* Returns true if <Candy.Core.connect> was first called with a domain instead of a jid as the first param.
*
* Returns:
* (Boolean)
*/
self.isAnonymousConnection = function() {
return _anonymousConnection;
};
/** Function: getOptions
* Gets options
*
* Returns:
* Object
*/
self.getOptions = function() {
return _options;
};
/** Function: getRoom
* Gets a specific room
*
* Parameters:
* (String) roomJid - JID of the room
*
* Returns:
* If the room is joined, instance of Candy.Core.ChatRoom, otherwise null.
*/
self.getRoom = function(roomJid) {
if (_rooms[roomJid]) {
return _rooms[roomJid];
}
return null;
};
/** Function: onWindowUnload
* window.onbeforeunload event which disconnects the client from the Jabber server.
*/
self.onWindowUnload = function() {
// Enable synchronous requests because Safari doesn't send asynchronous requests within unbeforeunload events.
// Only works properly when following patch is applied to strophejs: https://github.com/metajack/strophejs/issues/16/#issuecomment-600266
_connection.options.sync = true;
self.disconnect();
_connection.flush();
};
/** Function: rawInput
* (Overridden from Strophe.Connection.rawInput)
*
* Logs all raw input if debug is set to true.
*/
self.rawInput = function(data) {
this.log("RECV: " + data);
};
/** Function rawOutput
* (Overridden from Strophe.Connection.rawOutput)
*
* Logs all raw output if debug is set to true.
*/
self.rawOutput = function(data) {
this.log("SENT: " + data);
};
/** Function: log
* Overridden to do something useful if debug is set to true.
*
* See: Candy.Core#init
*/
self.log = function() {};
/** Function: warn
* Print a message to the browser's "info" log
* Enabled regardless of debug mode
*/
self.warn = function() {
Function.prototype.apply.call(console.warn, console, arguments);
};
/** Function: error
* Print a message to the browser's "error" log
* Enabled regardless of debug mode
*/
self.error = function() {
Function.prototype.apply.call(console.error, console, arguments);
};
return self;
}(Candy.Core || {}, Strophe, jQuery);
/** File: view.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global jQuery, Candy, window, Mustache, document */
/** Class: Candy.View
* The Candy View Class
*
* Parameters:
* (Candy.View) self - itself
* (jQuery) $ - jQuery
*/
Candy.View = function(self, $) {
/** PrivateObject: _current
* Object containing current container & roomJid which the client sees.
*/
var _current = {
container: null,
roomJid: null
}, /** PrivateObject: _options
*
* Options:
* (String) language - language to use
* (String) assets - path to assets (res) directory (with trailing slash)
* (Object) messages - limit: clean up message pane when n is reached / remove: remove n messages after limit has been reached
* (Object) crop - crop if longer than defined: message.nickname=15, message.body=1000, message.url=undefined (not cropped), roster.nickname=15
* (Bool) enableXHTML - [default: false] enables XHTML messages sending & displaying
*/
_options = {
language: "en",
assets: "res/",
messages: {
limit: 2e3,
remove: 500
},
crop: {
message: {
nickname: 15,
body: 1e3,
url: undefined
},
roster: {
nickname: 15
}
},
enableXHTML: false
}, /** PrivateFunction: _setupTranslation
* Set dictionary using jQuery.i18n plugin.
*
* See: view/translation.js
* See: libs/jquery-i18n/jquery.i18n.js
*
* Parameters:
* (String) language - Language identifier
*/
_setupTranslation = function(language) {
$.i18n.load(self.Translation[language]);
}, /** PrivateFunction: _registerObservers
* Register observers. Candy core will now notify the View on changes.
*/
_registerObservers = function() {
$(Candy).on("candy:core.chat.connection", self.Observer.Chat.Connection);
$(Candy).on("candy:core.chat.message", self.Observer.Chat.Message);
$(Candy).on("candy:core.login", self.Observer.Login);
$(Candy).on("candy:core.autojoin-missing", self.Observer.AutojoinMissing);
$(Candy).on("candy:core.presence", self.Observer.Presence.update);
$(Candy).on("candy:core.presence.leave", self.Observer.Presence.update);
$(Candy).on("candy:core.presence.room", self.Observer.Presence.update);
$(Candy).on("candy:core.presence.error", self.Observer.PresenceError);
$(Candy).on("candy:core.message", self.Observer.Message);
}, /** PrivateFunction: _registerWindowHandlers
* Register window focus / blur / resize handlers.
*
* jQuery.focus()/.blur() <= 1.5.1 do not work for IE < 9. Fortunately onfocusin/onfocusout will work for them.
*/
_registerWindowHandlers = function() {
if (Candy.Util.getIeVersion() < 9) {
$(document).focusin(Candy.View.Pane.Window.onFocus).focusout(Candy.View.Pane.Window.onBlur);
} else {
$(window).focus(Candy.View.Pane.Window.onFocus).blur(Candy.View.Pane.Window.onBlur);
}
$(window).resize(Candy.View.Pane.Chat.fitTabs);
}, /** PrivateFunction: _initToolbar
* Initialize toolbar.
*/
_initToolbar = function() {
self.Pane.Chat.Toolbar.init();
}, /** PrivateFunction: _delegateTooltips
* Delegate mouseenter on tooltipified element to <Candy.View.Pane.Chat.Tooltip.show>.
*/
_delegateTooltips = function() {
$("body").delegate("li[data-tooltip]", "mouseenter", Candy.View.Pane.Chat.Tooltip.show);
};
/** Function: init
* Initialize chat view (setup DOM, register handlers & observers)
*
* Parameters:
* (jQuery.element) container - Container element of the whole chat view
* (Object) options - Options: see _options field (value passed here gets extended by the default value in _options field)
*/
self.init = function(container, options) {
// #216
// Rename `resources` to `assets` but prevent installations from failing
// after upgrade
if (options.resources) {
options.assets = options.resources;
}
delete options.resources;
$.extend(true, _options, options);
_setupTranslation(_options.language);
// Set path to emoticons
Candy.Util.Parser.setEmoticonPath(this.getOptions().assets + "img/emoticons/");
// Start DOMination...
_current.container = container;
_current.container.html(Mustache.to_html(Candy.View.Template.Chat.pane, {
tooltipEmoticons: $.i18n._("tooltipEmoticons"),
tooltipSound: $.i18n._("tooltipSound"),
tooltipAutoscroll: $.i18n._("tooltipAutoscroll"),
tooltipStatusmessage: $.i18n._("tooltipStatusmessage"),
tooltipAdministration: $.i18n._("tooltipAdministration"),
tooltipUsercount: $.i18n._("tooltipUsercount"),
assetsPath: this.getOptions().assets
}, {
tabs: Candy.View.Template.Chat.tabs,
mobile: Candy.View.Template.Chat.mobileIcon,
rooms: Candy.View.Template.Chat.rooms,
modal: Candy.View.Template.Chat.modal,
toolbar: Candy.View.Template.Chat.toolbar
}));
// ... and let the elements dance.
_registerWindowHandlers();
_initToolbar();
_registerObservers();
_delegateTooltips();
};
/** Function: getCurrent
* Get current container & roomJid in an object.
*
* Returns:
* Object containing container & roomJid
*/
self.getCurrent = function() {
return _current;
};
/** Function: getOptions
* Gets options
*
* Returns:
* Object
*/
self.getOptions = function() {
return _options;
};
return self;
}(Candy.View || {}, jQuery);
/** File: util.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, MD5, Strophe, document, escape, jQuery */
/** Class: Candy.Util
* Candy utils
*
* Parameters:
* (Candy.Util) self - itself
* (jQuery) $ - jQuery
*/
Candy.Util = function(self, $) {
/** Function: jidToId
* Translates a jid to a MD5-Id
*
* Parameters:
* (String) jid - Jid
*
* Returns:
* MD5-ified jid
*/
self.jidToId = function(jid) {
return MD5.hexdigest(jid);
};
/** Function: escapeJid
* Escapes a jid
*
* See:
* XEP-0106
*
* Parameters:
* (String) jid - Jid
*
* Returns:
* (String) - escaped jid
*/
self.escapeJid = function(jid) {
var node = Strophe.escapeNode(Strophe.getNodeFromJid(jid)), domain = Strophe.getDomainFromJid(jid), resource = Strophe.getResourceFromJid(jid);
jid = node + "@" + domain;
if (resource) {
jid += "/" + resource;
}
return jid;
};
/** Function: unescapeJid
* Unescapes a jid (node & resource get unescaped)
*
* See:
* XEP-0106
*
* Parameters:
* (String) jid - Jid
*
* Returns:
* (String) - unescaped Jid
*/
self.unescapeJid = function(jid) {
var node = Strophe.unescapeNode(Strophe.getNodeFromJid(jid)), domain = Strophe.getDomainFromJid(jid), resource = Strophe.getResourceFromJid(jid);
jid = node + "@" + domain;
if (resource) {
jid += "/" + resource;
}
return jid;
};
/** Function: crop
* Crop a string with the specified length
*
* Parameters:
* (String) str - String to crop
* (Integer) len - Max length
*/
self.crop = function(str, len) {
if (str.length > len) {
str = str.substr(0, len - 3) + "...";
}
return str;
};
/** Function: parseAndCropXhtml
* Parses the XHTML and applies various Candy related filters to it.
*
* - Ensures it contains only valid XHTML
* - Crops text to a max length
* - Parses the text in order to display html
*
* Parameters:
* (String) str - String containing XHTML
* (Integer) len - Max text length
*/
self.parseAndCropXhtml = function(str, len) {
return $("<div/>").append(self.createHtml($(str).get(0), len)).html();
};
/** Function: setCookie
* Sets a new cookie
*
* Parameters:
* (String) name - cookie name
* (String) value - Value
* (Integer) lifetime_days - Lifetime in days
*/
self.setCookie = function(name, value, lifetime_days) {
var exp = new Date();
exp.setDate(new Date().getDate() + lifetime_days);
document.cookie = name + "=" + value + ";expires=" + exp.toUTCString() + ";path=/";
};
/** Function: cookieExists
* Tests if a cookie with the given name exists
*
* Parameters:
* (String) name - Cookie name
*
* Returns:
* (Boolean) - true/false
*/
self.cookieExists = function(name) {
return document.cookie.indexOf(name) > -1;
};
/** Function: getCookie
* Returns the cookie value if there's one with this name, otherwise returns undefined
*
* Parameters:
* (String) name - Cookie name
*
* Returns:
* Cookie value or undefined
*/
self.getCookie = function(name) {
if (document.cookie) {
var regex = new RegExp(escape(name) + "=([^;]*)", "gm"), matches = regex.exec(document.cookie);
if (matches) {
return matches[1];
}
}
};
/** Function: deleteCookie
* Deletes a cookie with the given name
*
* Parameters:
* (String) name - cookie name
*/
self.deleteCookie = function(name) {
document.cookie = name + "=;expires=Thu, 01-Jan-70 00:00:01 GMT;path=/";
};
/** Function: getPosLeftAccordingToWindowBounds
* Fetches the window width and element width
* and checks if specified position + element width is bigger
* than the window width.
*
* If this evaluates to true, the position gets substracted by the element width.
*
* Parameters:
* (jQuery.Element) elem - Element to position
* (Integer) pos - Position left
*
* Returns:
* Object containing `px` (calculated position in pixel) and `alignment` (alignment of the element in relation to pos, either 'left' or 'right')
*/
self.getPosLeftAccordingToWindowBounds = function(elem, pos) {
var windowWidth = $(document).width(), elemWidth = elem.outerWidth(), marginDiff = elemWidth - elem.outerWidth(true), backgroundPositionAlignment = "left";
if (pos + elemWidth >= windowWidth) {
pos -= elemWidth - marginDiff;
backgroundPositionAlignment = "right";
}
return {
px: pos,
backgroundPositionAlignment: backgroundPositionAlignment
};
};
/** Function: getPosTopAccordingToWindowBounds
* Fetches the window height and element height
* and checks if specified position + element height is bigger
* than the window height.
*
* If this evaluates to true, the position gets substracted by the element height.
*
* Parameters:
* (jQuery.Element) elem - Element to position
* (Integer) pos - Position top
*
* Returns:
* Object containing `px` (calculated position in pixel) and `alignment` (alignment of the element in relation to pos, either 'top' or 'bottom')
*/
self.getPosTopAccordingToWindowBounds = function(elem, pos) {
var windowHeight = $(document).height(), elemHeight = elem.outerHeight(), marginDiff = elemHeight - elem.outerHeight(true), backgroundPositionAlignment = "top";
if (pos + elemHeight >= windowHeight) {
pos -= elemHeight - marginDiff;
backgroundPositionAlignment = "bottom";
}
return {
px: pos,
backgroundPositionAlignment: backgroundPositionAlignment
};
};
/** Function: localizedTime
* Localizes ISO-8610 Date with the time/dateformat specified in the translation.
*
* See: libs/dateformat/dateFormat.js
* See: src/view/translation.js
* See: jquery-i18n/jquery.i18n.js
*
* Parameters:
* (String) dateTime - ISO-8610 Datetime
*
* Returns:
* If current date is equal to the date supplied, format with timeFormat, otherwise with dateFormat
*/
self.localizedTime = function(dateTime) {
if (dateTime === undefined) {
return undefined;
}
// See if we were passed a Date object
var date;
if (dateTime.toDateString) {
date = dateTime;
} else {
date = self.iso8601toDate(dateTime);
}
if (date.toDateString() === new Date().toDateString()) {
return date.format($.i18n._("timeFormat"));
} else {
return date.format($.i18n._("dateFormat"));
}
};
/** Function: iso8610toDate
* Parses a ISO-8610 Date to a Date-Object.
*
* Uses a fallback if the client's browser doesn't support it.
*
* Quote:
* ECMAScript revision 5 adds native support for ISO-8601 dates in the Date.parse method,
* but many browsers currently on the market (Safari 4, Chrome 4, IE 6-8) do not support it.
*
* Credits:
* <Colin Snover at http://zetafleet.com/blog/javascript-dateparse-for-iso-8601>
*
* Parameters:
* (String) date - ISO-8610 Date
*
* Returns:
* Date-Object
*/
self.iso8601toDate = function(date) {
var timestamp = Date.parse(date);
if (isNaN(timestamp)) {
var struct = /^(\d{4}|[+\-]\d{6})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?))?/.exec(date);
if (struct) {
var minutesOffset = 0;
if (struct[8] !== "Z") {
minutesOffset = +struct[10] * 60 + +struct[11];
if (struct[9] === "+") {
minutesOffset = -minutesOffset;
}
}
minutesOffset -= new Date().getTimezoneOffset();
return new Date(+struct[1], +struct[2] - 1, +struct[3], +struct[4], +struct[5] + minutesOffset, +struct[6], struct[7] ? +struct[7].substr(0, 3) : 0);
} else {
// XEP-0091 date
timestamp = Date.parse(date.replace(/^(\d{4})(\d{2})(\d{2})/, "$1-$2-$3") + "Z");
}
}
return new Date(timestamp);
};
/** Function: isEmptyObject
* IE7 doesn't work with jQuery.isEmptyObject (<=1.5.1), workaround.
*
* Parameters:
* (Object) obj - the object to test for
*
* Returns:
* Boolean true or false.
*/
self.isEmptyObject = function(obj) {
var prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
/** Function: forceRedraw
* Fix IE7 not redrawing under some circumstances.
*
* Parameters:
* (jQuery.element) elem - jQuery element to redraw
*/
self.forceRedraw = function(elem) {
elem.css({
display: "none"
});
setTimeout(function() {
this.css({
display: "block"
});
}.bind(elem), 1);
};
/** PrivateVariable: ie
* Checks for IE version
*
* From: http://stackoverflow.com/a/5574871/315242
*/
var ie = function() {
var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i");
while (// adds innerhtml and continues as long as all[0] is truthy
div.innerHTML = "<!--[if gt IE " + ++v + "]><i></i><![endif]-->", all[0]) {}
return v > 4 ? v : undef;
}();
/** Function: getIeVersion
* Returns local variable `ie` which you can use to detect which IE version
* is available.
*
* Use e.g. like this: if(Candy.Util.getIeVersion() < 9) alert('kaboom');
*/
self.getIeVersion = function() {
return ie;
};
/** Function: isMobile
* Checks to see if we're on a mobile device.
*/
self.isMobile = function() {
var check = false;
(function(a) {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|android|ipad|playbook|silk|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
check = true;
}
})(navigator.userAgent || navigator.vendor || window.opera);
return check;
};
/** Class: Candy.Util.Parser
* Parser for emoticons, links and also supports escaping.
*/
self.Parser = {
/** Function: jid
* Parse a JID into an object with each element
*
* Parameters:
* (String) jid - The string representation of a JID
*/
jid: function(jid) {
var r = /^(([^@]+)@)?([^\/]+)(\/(.*))?$/i, a = jid.match(r);
if (!a) {
throw "not a valid jid (" + jid + ")";
}
return {
node: a[2],
domain: a[3],
resource: a[4]
};
},
/** PrivateVariable: _emoticonPath
* Path to emoticons.
*
* Use setEmoticonPath() to change it
*/
_emoticonPath: "",
/** Function: setEmoticonPath
* Set emoticons location.
*
* Parameters:
* (String) path - location of emoticons with trailing slash
*/
setEmoticonPath: function(path) {
this._emoticonPath = path;
},
/** Array: emoticons
* Array containing emoticons to be replaced by their images.
*
* Can be overridden/extended.
*/
emoticons: [ {
plain: ":)",
regex: /((\s):-?\)|:-?\)(\s|$))/gm,
image: "Smiling.png"
}, {
plain: ";)",
regex: /((\s);-?\)|;-?\)(\s|$))/gm,
image: "Winking.png"
}, {
plain: ":D",
regex: /((\s):-?D|:-?D(\s|$))/gm,
image: "Grinning.png"
}, {
plain: ";D",
regex: /((\s);-?D|;-?D(\s|$))/gm,
image: "Grinning_Winking.png"
}, {
plain: ":(",
regex: /((\s):-?\(|:-?\((\s|$))/gm,
image: "Unhappy.png"
}, {
plain: "^^",
regex: /((\s)\^\^|\^\^(\s|$))/gm,
image: "Happy_3.png"
}, {
plain: ":P",
regex: /((\s):-?P|:-?P(\s|$))/gim,
image: "Tongue_Out.png"
}, {
plain: ";P",
regex: /((\s);-?P|;-?P(\s|$))/gim,
image: "Tongue_Out_Winking.png"
}, {
plain: ":S",
regex: /((\s):-?S|:-?S(\s|$))/gim,
image: "Confused.png"
}, {
plain: ":/",
regex: /((\s):-?\/|:-?\/(\s|$))/gm,
image: "Uncertain.png"
}, {
plain: "8)",
regex: /((\s)8-?\)|8-?\)(\s|$))/gm,
image: "Sunglasses.png"
}, {
plain: "$)",
regex: /((\s)\$-?\)|\$-?\)(\s|$))/gm,
image: "Greedy.png"
}, {
plain: "oO",
regex: /((\s)oO|oO(\s|$))/gm,
image: "Huh.png"
}, {
plain: ":x",
regex: /((\s):x|:x(\s|$))/gm,
image: "Lips_Sealed.png"
}, {
plain: ":666:",
regex: /((\s):666:|:666:(\s|$))/gm,
image: "Devil.png"
}, {
plain: "<3",
regex: /((\s)<3|<3(\s|$))/gm,
image: "Heart.png"
} ],
/** Function: emotify
* Replaces text-emoticons with their image equivalent.
*
* Parameters:
* (String) text - Text to emotify
*
* Returns:
* Emotified text
*/
emotify: function(text) {
var i;
for (i = this.emoticons.length - 1; i >= 0; i--) {
text = text.replace(this.emoticons[i].regex, '$2<img class="emoticon" alt="$1" title="$1" src="' + this._emoticonPath + this.emoticons[i].image + '" />$3');
}
return text;
},
/** Function: linkify
* Replaces URLs with a HTML-link.
* big regex adapted from https://gist.github.com/dperini/729294 - Diego Perini, MIT license.
*
* Parameters:
* (String) text - Text to linkify
*
* Returns:
* Linkified text
*/
linkify: function(text) {
text = text.replace(/(^|[^\/])(www\.[^\.]+\.[\S]+(\b|$))/gi, "$1http://$2");
return text.replace(/(\b(?:(?:https?|ftp|file):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:1\d\d|2[01]\d|22[0-3]|[1-9]\d?)(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?)/gi, function(matched, url) {
return '<a href="' + url + '" target="_blank">' + self.crop(url, Candy.View.getOptions().crop.message.url) + "</a>";
});
},
/** Function: escape
* Escapes a text using a jQuery function (like htmlspecialchars in PHP)
*
* Parameters:
* (String) text - Text to escape
*
* Returns:
* Escaped text
*/
escape: function(text) {
return $("<div/>").text(text).html();
},
/** Function: nl2br
* replaces newline characters with a <br/> to make multi line messages look nice
*
* Parameters:
* (String) text - Text to process
*
* Returns:
* Processed text
*/
nl2br: function(text) {
return text.replace(/\r\n|\r|\n/g, "<br />");
},
/** Function: all
* Does everything of the parser: escaping, linkifying and emotifying.
*
* Parameters:
* (String) text - Text to parse
*
* Returns:
* (String) Parsed text
*/
all: function(text) {
if (text) {
text = this.escape(text);
text = this.linkify(text);
text = this.emotify(text);
text = this.nl2br(text);
}
return text;
}
};
/** Function: createHtml
* Copy an HTML DOM element into an XML DOM.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* It's a function copied & adapted from [Strophe.js core.js](https://github.com/strophe/strophejs/blob/master/src/core.js).
*
* Parameters:
* (HTMLElement) elem - A DOM element.
* (Integer) maxLength - Max length of text
* (Integer) currentLength - Current accumulated text length
*
* Returns:
* A new, copied DOM element tree.
*/
self.createHtml = function(elem, maxLength, currentLength) {
/* jshint -W073 */
currentLength = currentLength || 0;
var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue;
if (elem.nodeType === Strophe.ElementType.NORMAL) {
tag = elem.nodeName.toLowerCase();
if (Strophe.XHTML.validTag(tag)) {
try {
el = $("<" + tag + "/>");
for (i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
attribute = Strophe.XHTML.attributes[tag][i];
value = elem.getAttribute(attribute);
if (typeof value === "undefined" || value === null || value === "" || value === false || value === 0) {
continue;
}
if (attribute === "style" && typeof value === "object") {
if (typeof value.cssText !== "undefined") {
value = value.cssText;
}
}
// filter out invalid css styles
if (attribute === "style") {
css = [];
cssAttrs = value.split(";");
for (j = 0; j < cssAttrs.length; j++) {
attr = cssAttrs[j].split(":");
cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
if (Strophe.XHTML.validCSS(cssName)) {
cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
css.push(cssName + ": " + cssValue);
}
}
if (css.length > 0) {
value = css.join("; ");
el.attr(attribute, value);
}
} else {
el.attr(attribute, value);
}
}
for (i = 0; i < elem.childNodes.length; i++) {
el.append(self.createHtml(elem.childNodes[i], maxLength, currentLength));
}
} catch (e) {
// invalid elements
Candy.Core.warn("[Util:createHtml] Error while parsing XHTML:", e);
el = Strophe.xmlTextNode("");
}
} else {
el = Strophe.xmlGenerator().createDocumentFragment();
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(self.createHtml(elem.childNodes[i], maxLength, currentLength));
}
}
} else if (elem.nodeType === Strophe.ElementType.FRAGMENT) {
el = Strophe.xmlGenerator().createDocumentFragment();
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(self.createHtml(elem.childNodes[i], maxLength, currentLength));
}
} else if (elem.nodeType === Strophe.ElementType.TEXT) {
var text = elem.nodeValue;
currentLength += text.length;
if (maxLength && currentLength > maxLength) {
text = text.substring(0, maxLength);
}
text = Candy.Util.Parser.all(text);
el = $.parseHTML(text);
}
return el;
};
return self;
}(Candy.Util || {}, jQuery);
/** File: action.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, $iq, navigator, Candy, $pres, Strophe, jQuery, $msg */
/** Class: Candy.Core.Action
* Chat Actions (basicly a abstraction of Jabber commands)
*
* Parameters:
* (Candy.Core.Action) self - itself
* (Strophe) Strophe - Strophe
* (jQuery) $ - jQuery
*/
Candy.Core.Action = function(self, Strophe, $) {
/** Class: Candy.Core.Action.Jabber
* Jabber actions
*/
self.Jabber = {
/** Function: Version
* Replies to a version request
*
* Parameters:
* (jQuery.element) msg - jQuery element
*/
Version: function(msg) {
Candy.Core.getConnection().sendIQ($iq({
type: "result",
to: Candy.Util.escapeJid(msg.attr("from")),
from: Candy.Util.escapeJid(msg.attr("to")),
id: msg.attr("id")
}).c("query", {
xmlns: Strophe.NS.VERSION
}).c("name", Candy.about.name).up().c("version", Candy.about.version).up().c("os", navigator.userAgent));
},
/** Function: SetNickname
* Sets the supplied nickname for all rooms (if parameter "room" is not specified) or
* sets it only for the specified rooms
*
* Parameters:
* (String) nickname - New nickname
* (Array) rooms - Rooms
*/
SetNickname: function(nickname, rooms) {
rooms = rooms instanceof Array ? rooms : Candy.Core.getRooms();
var roomNick, presence, conn = Candy.Core.getConnection();
$.each(rooms, function(roomJid) {
roomNick = Candy.Util.escapeJid(roomJid + "/" + nickname);
presence = $pres({
to: roomNick,
from: conn.jid,
id: "pres:" + conn.getUniqueId()
});
Candy.Core.getConnection().send(presence);
});
},
/** Function: Roster
* Sends a request for a roster
*/
Roster: function() {
var roster = Candy.Core.getConnection().roster, options = Candy.Core.getOptions();
roster.registerCallback(Candy.Core.Event.Jabber.RosterPush);
$.each(options.initialRosterItems, function(i, item) {
// Blank out resources because their cached value is not relevant
item.resources = {};
});
roster.get(Candy.Core.Event.Jabber.RosterFetch, options.initialRosterVersion, options.initialRosterItems);
// Bootstrap our roster with cached items
Candy.Core.Event.Jabber.RosterLoad(roster.items);
},
/** Function: Presence
* Sends a request for presence
*
* Parameters:
* (Object) attr - Optional attributes
* (Strophe.Builder) el - Optional element to include in presence stanza
*/
Presence: function(attr, el) {
var conn = Candy.Core.getConnection();
attr = attr || {};
if (!attr.id) {
attr.id = "pres:" + conn.getUniqueId();
}
var pres = $pres(attr).c("priority").t(Candy.Core.getOptions().presencePriority.toString()).up().c("c", conn.caps.generateCapsAttrs()).up();
if (el) {
pres.node.appendChild(el.node);
}
conn.send(pres.tree());
},
/** Function: Services
* Sends a request for disco items
*/
Services: function() {
Candy.Core.getConnection().sendIQ($iq({
type: "get",
xmlns: Strophe.NS.CLIENT
}).c("query", {
xmlns: Strophe.NS.DISCO_ITEMS
}).tree());
},
/** Function: Autojoin
* When Candy.Core.getOptions().autojoin is true, request autojoin bookmarks (OpenFire)
*
* Otherwise, if Candy.Core.getOptions().autojoin is an array, join each channel specified.
* Channel can be in jid:password format to pass room password if needed.
* Triggers:
* candy:core.autojoin-missing in case no autojoin info has been found
*/
Autojoin: function() {
// Request bookmarks
if (Candy.Core.getOptions().autojoin === true) {
Candy.Core.getConnection().sendIQ($iq({
type: "get",
xmlns: Strophe.NS.CLIENT
}).c("query", {
xmlns: Strophe.NS.PRIVATE
}).c("storage", {
xmlns: Strophe.NS.BOOKMARKS
}).tree());
var pubsubBookmarkRequest = Candy.Core.getConnection().getUniqueId("pubsub");
Candy.Core.addHandler(Candy.Core.Event.Jabber.Bookmarks, Strophe.NS.PUBSUB, "iq", "result", pubsubBookmarkRequest);
Candy.Core.getConnection().sendIQ($iq({
type: "get",
id: pubsubBookmarkRequest
}).c("pubsub", {
xmlns: Strophe.NS.PUBSUB
}).c("items", {
node: Strophe.NS.BOOKMARKS
}).tree());
} else if ($.isArray(Candy.Core.getOptions().autojoin)) {
$.each(Candy.Core.getOptions().autojoin, function() {
self.Jabber.Room.Join.apply(null, this.valueOf().split(":", 2));
});
} else {
/** Event: candy:core.autojoin-missing
* Triggered when no autojoin information has been found
*/
$(Candy).triggerHandler("candy:core.autojoin-missing");
}
},
/** Function: EnableCarbons
* Enable message carbons (XEP-0280)
*/
EnableCarbons: function() {
Candy.Core.getConnection().sendIQ($iq({
type: "set"
}).c("enable", {
xmlns: Strophe.NS.CARBONS
}).tree());
},
/** Function: ResetIgnoreList
* Create new ignore privacy list (and reset the previous one, if it exists).
*/
ResetIgnoreList: function() {
Candy.Core.getConnection().sendIQ($iq({
type: "set",
from: Candy.Core.getUser().getEscapedJid()
}).c("query", {
xmlns: Strophe.NS.PRIVACY
}).c("list", {
name: "ignore"
}).c("item", {
action: "allow",
order: "0"
}).tree());
},
/** Function: RemoveIgnoreList
* Remove an existing ignore list.
*/
RemoveIgnoreList: function() {
Candy.Core.getConnection().sendIQ($iq({
type: "set",
from: Candy.Core.getUser().getEscapedJid()
}).c("query", {
xmlns: Strophe.NS.PRIVACY
}).c("list", {
name: "ignore"
}).tree());
},
/** Function: GetIgnoreList
* Get existing ignore privacy list when connecting.
*/
GetIgnoreList: function() {
var iq = $iq({
type: "get",
from: Candy.Core.getUser().getEscapedJid()
}).c("query", {
xmlns: Strophe.NS.PRIVACY
}).c("list", {
name: "ignore"
}).tree();
var iqId = Candy.Core.getConnection().sendIQ(iq);
// add handler (<#200 at https://github.com/candy-chat/candy/issues/200>)
Candy.Core.addHandler(Candy.Core.Event.Jabber.PrivacyList, null, "iq", null, iqId);
},
/** Function: SetIgnoreListActive
* Set ignore privacy list active
*/
SetIgnoreListActive: function() {
Candy.Core.getConnection().sendIQ($iq({
type: "set",
from: Candy.Core.getUser().getEscapedJid()
}).c("query", {
xmlns: Strophe.NS.PRIVACY
}).c("active", {
name: "ignore"
}).tree());
},
/** Function: GetJidIfAnonymous
* On anonymous login, initially we don't know the jid and as a result, Candy.Core._user doesn't have a jid.
* Check if user doesn't have a jid and get it if necessary from the connection.
*/
GetJidIfAnonymous: function() {
if (!Candy.Core.getUser().getJid()) {
Candy.Core.log("[Jabber] Anonymous login");
Candy.Core.getUser().data.jid = Candy.Core.getConnection().jid;
}
},
/** Class: Candy.Core.Action.Jabber.Room
* Room-specific commands
*/
Room: {
/** Function: Join
* Requests disco of specified room and joins afterwards.
*
* TODO:
* maybe we should wait for disco and later join the room?
* but what if we send disco but don't want/can join the room
*
* Parameters:
* (String) roomJid - Room to join
* (String) password - [optional] Password for the room
*/
Join: function(roomJid, password) {
self.Jabber.Room.Disco(roomJid);
roomJid = Candy.Util.escapeJid(roomJid);
var conn = Candy.Core.getConnection(), roomNick = roomJid + "/" + Candy.Core.getUser().getNick(), pres = $pres({
to: roomNick,
id: "pres:" + conn.getUniqueId()
}).c("x", {
xmlns: Strophe.NS.MUC
});
if (password) {
pres.c("password").t(password);
}
pres.up().c("c", conn.caps.generateCapsAttrs());
conn.send(pres.tree());
},
/** Function: Leave
* Leaves a room.
*
* Parameters:
* (String) roomJid - Room to leave
*/
Leave: function(roomJid) {
var user = Candy.Core.getRoom(roomJid).getUser();
if (user) {
Candy.Core.getConnection().muc.leave(roomJid, user.getNick(), function() {});
}
},
/** Function: Disco
* Requests <disco info of a room at http://xmpp.org/extensions/xep-0045.html#disco-roominfo>.
*
* Parameters:
* (String) roomJid - Room to get info for
*/
Disco: function(roomJid) {
Candy.Core.getConnection().sendIQ($iq({
type: "get",
from: Candy.Core.getUser().getEscapedJid(),
to: Candy.Util.escapeJid(roomJid)
}).c("query", {
xmlns: Strophe.NS.DISCO_INFO
}).tree());
},
/** Function: Message
* Send message
*
* Parameters:
* (String) roomJid - Room to which send the message into
* (String) msg - Message
* (String) type - "groupchat" or "chat" ("chat" is for private messages)
* (String) xhtmlMsg - XHTML formatted message [optional]
*
* Returns:
* (Boolean) - true if message is not empty after trimming, false otherwise.
*/
Message: function(roomJid, msg, type, xhtmlMsg) {
// Trim message
msg = $.trim(msg);
if (msg === "") {
return false;
}
var nick = null;
if (type === "chat") {
nick = Strophe.getResourceFromJid(roomJid);
roomJid = Strophe.getBareJidFromJid(roomJid);
}
// muc takes care of the escaping now.
Candy.Core.getConnection().muc.message(roomJid, nick, msg, xhtmlMsg, type);
return true;
},
/** Function: Invite
* Sends an invite stanza to multiple JIDs
*
* Parameters:
* (String) roomJid - Room to which send the message into
* (Array) invitees - Array of JIDs to be invited to the room
* (String) reason - Message to include with the invitation [optional]
* (String) password - Password for the MUC, if required [optional]
*/
Invite: function(roomJid, invitees, reason, password) {
reason = $.trim(reason);
var message = $msg({
to: roomJid
});
var x = message.c("x", {
xmlns: Strophe.NS.MUC_USER
});
$.each(invitees, function(i, invitee) {
invitee = Strophe.getBareJidFromJid(invitee);
x.c("invite", {
to: invitee
});
if (typeof reason !== "undefined" && reason !== "") {
x.c("reason", reason);
}
});
if (typeof password !== "undefined" && password !== "") {
x.c("password", password);
}
Candy.Core.getConnection().send(message);
},
/** Function: IgnoreUnignore
* Checks if the user is already ignoring the target user, if yes: unignore him, if no: ignore him.
*
* Uses the ignore privacy list set on connecting.
*
* Parameters:
* (String) userJid - Target user jid
*/
IgnoreUnignore: function(userJid) {
Candy.Core.getUser().addToOrRemoveFromPrivacyList("ignore", userJid);
Candy.Core.Action.Jabber.Room.UpdatePrivacyList();
},
/** Function: UpdatePrivacyList
* Updates privacy list according to the privacylist in the currentUser
*/
UpdatePrivacyList: function() {
var currentUser = Candy.Core.getUser(), iq = $iq({
type: "set",
from: currentUser.getEscapedJid()
}).c("query", {
xmlns: "jabber:iq:privacy"
}).c("list", {
name: "ignore"
}), privacyList = currentUser.getPrivacyList("ignore");
if (privacyList.length > 0) {
$.each(privacyList, function(index, jid) {
iq.c("item", {
type: "jid",
value: Candy.Util.escapeJid(jid),
action: "deny",
order: index
}).c("message").up().up();
});
} else {
iq.c("item", {
action: "allow",
order: "0"
});
}
Candy.Core.getConnection().sendIQ(iq.tree());
},
/** Class: Candy.Core.Action.Jabber.Room.Admin
* Room administration commands
*/
Admin: {
/** Function: UserAction
* Kick or ban a user
*
* Parameters:
* (String) roomJid - Room in which the kick/ban should be done
* (String) userJid - Victim
* (String) type - "kick" or "ban"
* (String) msg - Reason
*
* Returns:
* (Boolean) - true if sent successfully, false if type is not one of "kick" or "ban".
*/
UserAction: function(roomJid, userJid, type, reason) {
roomJid = Candy.Util.escapeJid(roomJid);
userJid = Candy.Util.escapeJid(userJid);
var itemObj = {
nick: Strophe.getResourceFromJid(userJid)
};
switch (type) {
case "kick":
itemObj.role = "none";
break;
case "ban":
itemObj.affiliation = "outcast";
break;
default:
return false;
}
Candy.Core.getConnection().sendIQ($iq({
type: "set",
from: Candy.Core.getUser().getEscapedJid(),
to: roomJid
}).c("query", {
xmlns: Strophe.NS.MUC_ADMIN
}).c("item", itemObj).c("reason").t(reason).tree());
return true;
},
/** Function: SetSubject
* Sets subject (topic) of a room.
*
* Parameters:
* (String) roomJid - Room
* (String) subject - Subject to set
*/
SetSubject: function(roomJid, subject) {
Candy.Core.getConnection().muc.setTopic(Candy.Util.escapeJid(roomJid), subject);
}
}
}
};
return self;
}(Candy.Core.Action || {}, Strophe, jQuery);
/** File: chatRoom.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Strophe */
/** Class: Candy.Core.ChatRoom
* Candy Chat Room
*
* Parameters:
* (String) roomJid - Room jid
*/
Candy.Core.ChatRoom = function(roomJid) {
/** Object: room
* Object containing roomJid and name.
*/
this.room = {
jid: roomJid,
name: Strophe.getNodeFromJid(roomJid)
};
/** Variable: user
* Current local user of this room.
*/
this.user = null;
/** Variable: Roster
* Candy.Core.ChatRoster instance
*/
this.roster = new Candy.Core.ChatRoster();
};
/** Function: setUser
* Set user of this room.
*
* Parameters:
* (Candy.Core.ChatUser) user - Chat user
*/
Candy.Core.ChatRoom.prototype.setUser = function(user) {
this.user = user;
};
/** Function: getUser
* Get current local user
*
* Returns:
* (Object) - Candy.Core.ChatUser instance or null
*/
Candy.Core.ChatRoom.prototype.getUser = function() {
return this.user;
};
/** Function: getJid
* Get room jid
*
* Returns:
* (String) - Room jid
*/
Candy.Core.ChatRoom.prototype.getJid = function() {
return this.room.jid;
};
/** Function: setName
* Set room name
*
* Parameters:
* (String) name - Room name
*/
Candy.Core.ChatRoom.prototype.setName = function(name) {
this.room.name = name;
};
/** Function: getName
* Get room name
*
* Returns:
* (String) - Room name
*/
Candy.Core.ChatRoom.prototype.getName = function() {
return this.room.name;
};
/** Function: setRoster
* Set roster of room
*
* Parameters:
* (Candy.Core.ChatRoster) roster - Chat roster
*/
Candy.Core.ChatRoom.prototype.setRoster = function(roster) {
this.roster = roster;
};
/** Function: getRoster
* Get roster
*
* Returns
* (Candy.Core.ChatRoster) - instance
*/
Candy.Core.ChatRoom.prototype.getRoster = function() {
return this.roster;
};
/** File: chatRoster.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy */
/** Class: Candy.Core.ChatRoster
* Chat Roster
*/
Candy.Core.ChatRoster = function() {
/** Object: items
* Roster items
*/
this.items = {};
};
/** Function: add
* Add user to roster
*
* Parameters:
* (Candy.Core.ChatUser) user - User to add
*/
Candy.Core.ChatRoster.prototype.add = function(user) {
this.items[user.getJid()] = user;
};
/** Function: remove
* Remove user from roster
*
* Parameters:
* (String) jid - User jid
*/
Candy.Core.ChatRoster.prototype.remove = function(jid) {
delete this.items[jid];
};
/** Function: get
* Get user from roster
*
* Parameters:
* (String) jid - User jid
*
* Returns:
* (Candy.Core.ChatUser) - User
*/
Candy.Core.ChatRoster.prototype.get = function(jid) {
return this.items[jid];
};
/** Function: getAll
* Get all items
*
* Returns:
* (Object) - all roster items
*/
Candy.Core.ChatRoster.prototype.getAll = function() {
return this.items;
};
/** File: chatUser.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Strophe */
/** Class: Candy.Core.ChatUser
* Chat User
*/
Candy.Core.ChatUser = function(jid, nick, affiliation, role, realJid) {
/** Constant: ROLE_MODERATOR
* Moderator role
*/
this.ROLE_MODERATOR = "moderator";
/** Constant: AFFILIATION_OWNER
* Affiliation owner
*/
this.AFFILIATION_OWNER = "owner";
/** Object: data
* User data containing:
* - jid
* - realJid
* - nick
* - affiliation
* - role
* - privacyLists
* - customData to be used by e.g. plugins
*/
this.data = {
jid: jid,
realJid: realJid,
nick: Strophe.unescapeNode(nick),
affiliation: affiliation,
role: role,
privacyLists: {},
customData: {},
previousNick: undefined,
status: "unavailable"
};
};
/** Function: getJid
* Gets an unescaped user jid
*
* See:
* <Candy.Util.unescapeJid>
*
* Returns:
* (String) - jid
*/
Candy.Core.ChatUser.prototype.getJid = function() {
if (this.data.jid) {
return Candy.Util.unescapeJid(this.data.jid);
}
return;
};
/** Function: getEscapedJid
* Escapes the user's jid (node & resource get escaped)
*
* See:
* <Candy.Util.escapeJid>
*
* Returns:
* (String) - escaped jid
*/
Candy.Core.ChatUser.prototype.getEscapedJid = function() {
return Candy.Util.escapeJid(this.data.jid);
};
/** Function: setJid
* Sets a user's jid
*
* Parameters:
* (String) jid - New Jid
*/
Candy.Core.ChatUser.prototype.setJid = function(jid) {
this.data.jid = jid;
};
/** Function: getRealJid
* Gets an unescaped real jid if known
*
* See:
* <Candy.Util.unescapeJid>
*
* Returns:
* (String) - realJid
*/
Candy.Core.ChatUser.prototype.getRealJid = function() {
if (this.data.realJid) {
return Candy.Util.unescapeJid(this.data.realJid);
}
return;
};
/** Function: getNick
* Gets user nick
*
* Returns:
* (String) - nick
*/
Candy.Core.ChatUser.prototype.getNick = function() {
return Strophe.unescapeNode(this.data.nick);
};
/** Function: setNick
* Sets a user's nick
*
* Parameters:
* (String) nick - New nick
*/
Candy.Core.ChatUser.prototype.setNick = function(nick) {
this.data.nick = nick;
};
/** Function: getName
* Gets user's name (from contact or nick)
*
* Returns:
* (String) - name
*/
Candy.Core.ChatUser.prototype.getName = function() {
var contact = this.getContact();
if (contact) {
return contact.getName();
} else {
return this.getNick();
}
};
/** Function: getRole
* Gets user role
*
* Returns:
* (String) - role
*/
Candy.Core.ChatUser.prototype.getRole = function() {
return this.data.role;
};
/** Function: setRole
* Sets user role
*
* Parameters:
* (String) role - Role
*/
Candy.Core.ChatUser.prototype.setRole = function(role) {
this.data.role = role;
};
/** Function: setAffiliation
* Sets user affiliation
*
* Parameters:
* (String) affiliation - new affiliation
*/
Candy.Core.ChatUser.prototype.setAffiliation = function(affiliation) {
this.data.affiliation = affiliation;
};
/** Function: getAffiliation
* Gets user affiliation
*
* Returns:
* (String) - affiliation
*/
Candy.Core.ChatUser.prototype.getAffiliation = function() {
return this.data.affiliation;
};
/** Function: isModerator
* Check if user is moderator. Depends on the room.
*
* Returns:
* (Boolean) - true if user has role moderator or affiliation owner
*/
Candy.Core.ChatUser.prototype.isModerator = function() {
return this.getRole() === this.ROLE_MODERATOR || this.getAffiliation() === this.AFFILIATION_OWNER;
};
/** Function: addToOrRemoveFromPrivacyList
* Convenience function for adding/removing users from ignore list.
*
* Check if user is already in privacy list. If yes, remove it. If no, add it.
*
* Parameters:
* (String) list - To which privacy list the user should be added / removed from. Candy supports curently only the "ignore" list.
* (String) jid - User jid to add/remove
*
* Returns:
* (Array) - Current privacy list.
*/
Candy.Core.ChatUser.prototype.addToOrRemoveFromPrivacyList = function(list, jid) {
if (!this.data.privacyLists[list]) {
this.data.privacyLists[list] = [];
}
var index = -1;
if ((index = this.data.privacyLists[list].indexOf(jid)) !== -1) {
this.data.privacyLists[list].splice(index, 1);
} else {
this.data.privacyLists[list].push(jid);
}
return this.data.privacyLists[list];
};
/** Function: getPrivacyList
* Returns the privacy list of the listname of the param.
*
* Parameters:
* (String) list - To which privacy list the user should be added / removed from. Candy supports curently only the "ignore" list.
*
* Returns:
* (Array) - Privacy List
*/
Candy.Core.ChatUser.prototype.getPrivacyList = function(list) {
if (!this.data.privacyLists[list]) {
this.data.privacyLists[list] = [];
}
return this.data.privacyLists[list];
};
/** Function: setPrivacyLists
* Sets privacy lists.
*
* Parameters:
* (Object) lists - List object
*/
Candy.Core.ChatUser.prototype.setPrivacyLists = function(lists) {
this.data.privacyLists = lists;
};
/** Function: isInPrivacyList
* Tests if this user ignores the user provided by jid.
*
* Parameters:
* (String) list - Privacy list
* (String) jid - Jid to test for
*
* Returns:
* (Boolean)
*/
Candy.Core.ChatUser.prototype.isInPrivacyList = function(list, jid) {
if (!this.data.privacyLists[list]) {
return false;
}
return this.data.privacyLists[list].indexOf(jid) !== -1;
};
/** Function: setCustomData
* Stores custom data
*
* Parameter:
* (Object) data - Object containing custom data
*/
Candy.Core.ChatUser.prototype.setCustomData = function(data) {
this.data.customData = data;
};
/** Function: getCustomData
* Retrieve custom data
*
* Returns:
* (Object) - Object containing custom data
*/
Candy.Core.ChatUser.prototype.getCustomData = function() {
return this.data.customData;
};
/** Function: setPreviousNick
* If user has nickname changed, set previous nickname.
*
* Parameters:
* (String) previousNick - the previous nickname
*/
Candy.Core.ChatUser.prototype.setPreviousNick = function(previousNick) {
this.data.previousNick = previousNick;
};
/** Function: hasNicknameChanged
* Gets the previous nickname if available.
*
* Returns:
* (String) - previous nickname
*/
Candy.Core.ChatUser.prototype.getPreviousNick = function() {
return this.data.previousNick;
};
/** Function: getContact
* Gets the contact matching this user from our roster
*
* Returns:
* (Candy.Core.Contact) - contact from roster
*/
Candy.Core.ChatUser.prototype.getContact = function() {
return Candy.Core.getRoster().get(Strophe.getBareJidFromJid(this.data.realJid));
};
/** Function: setStatus
* Set the user's status
*
* Parameters:
* (String) status - the new status
*/
Candy.Core.ChatUser.prototype.setStatus = function(status) {
this.data.status = status;
};
/** Function: getStatus
* Gets the user's status.
*
* Returns:
* (String) - status
*/
Candy.Core.ChatUser.prototype.getStatus = function() {
return this.data.status;
};
/** File: contact.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Strophe, $ */
/** Class: Candy.Core.Contact
* Roster contact
*/
Candy.Core.Contact = function(stropheRosterItem) {
/** Object: data
* Strophe Roster plugin item model containing:
* - jid
* - name
* - subscription
* - groups
*/
this.data = stropheRosterItem;
};
/** Function: getJid
* Gets an unescaped user jid
*
* See:
* <Candy.Util.unescapeJid>
*
* Returns:
* (String) - jid
*/
Candy.Core.Contact.prototype.getJid = function() {
if (this.data.jid) {
return Candy.Util.unescapeJid(this.data.jid);
}
return;
};
/** Function: getEscapedJid
* Escapes the user's jid (node & resource get escaped)
*
* See:
* <Candy.Util.escapeJid>
*
* Returns:
* (String) - escaped jid
*/
Candy.Core.Contact.prototype.getEscapedJid = function() {
return Candy.Util.escapeJid(this.data.jid);
};
/** Function: getName
* Gets user name
*
* Returns:
* (String) - name
*/
Candy.Core.Contact.prototype.getName = function() {
if (!this.data.name) {
return this.getJid();
}
return Strophe.unescapeNode(this.data.name);
};
/** Function: getNick
* Gets user name
*
* Returns:
* (String) - name
*/
Candy.Core.Contact.prototype.getNick = Candy.Core.Contact.prototype.getName;
/** Function: getSubscription
* Gets user subscription
*
* Returns:
* (String) - subscription
*/
Candy.Core.Contact.prototype.getSubscription = function() {
if (!this.data.subscription) {
return "none";
}
return this.data.subscription;
};
/** Function: getGroups
* Gets user groups
*
* Returns:
* (Array) - groups
*/
Candy.Core.Contact.prototype.getGroups = function() {
return this.data.groups;
};
/** Function: getStatus
* Gets user status as an aggregate of all resources
*
* Returns:
* (String) - aggregate status, one of chat|dnd|available|away|xa|unavailable
*/
Candy.Core.Contact.prototype.getStatus = function() {
var status = "unavailable", self = this, highestResourcePriority;
$.each(this.data.resources, function(resource, obj) {
var resourcePriority;
if (obj.priority === undefined || obj.priority === "") {
resourcePriority = 0;
} else {
resourcePriority = parseInt(obj.priority, 10);
}
if (obj.show === "" || obj.show === null || obj.show === undefined) {
// TODO: Submit this as a bugfix to strophejs-plugins' roster plugin
obj.show = "available";
}
if (highestResourcePriority === undefined || highestResourcePriority < resourcePriority) {
// This resource is higher priority than the ones we've checked so far, override with this one
status = obj.show;
highestResourcePriority = resourcePriority;
} else if (highestResourcePriority === resourcePriority) {
// Two resources with the same priority means we have to weight their status
if (self._weightForStatus(status) > self._weightForStatus(obj.show)) {
status = obj.show;
}
}
});
return status;
};
Candy.Core.Contact.prototype._weightForStatus = function(status) {
switch (status) {
case "chat":
case "dnd":
return 1;
case "available":
case "":
return 2;
case "away":
return 3;
case "xa":
return 4;
case "unavailable":
return 5;
}
};
/** File: event.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Strophe, jQuery */
/** Class: Candy.Core.Event
* Chat Events
*
* Parameters:
* (Candy.Core.Event) self - itself
* (Strophe) Strophe - Strophe
* (jQuery) $ - jQuery
*/
Candy.Core.Event = function(self, Strophe, $) {
/** Function: Login
* Notify view that the login window should be displayed
*
* Parameters:
* (String) presetJid - Preset user JID
*
* Triggers:
* candy:core.login using {presetJid}
*/
self.Login = function(presetJid) {
/** Event: candy:core.login
* Triggered when the login window should be displayed
*
* Parameters:
* (String) presetJid - Preset user JID
*/
$(Candy).triggerHandler("candy:core.login", {
presetJid: presetJid
});
};
/** Class: Candy.Core.Event.Strophe
* Strophe-related events
*/
self.Strophe = {
/** Function: Connect
* Acts on strophe status events and notifies view.
*
* Parameters:
* (Strophe.Status) status - Strophe statuses
*
* Triggers:
* candy:core.chat.connection using {status}
*/
Connect: function(status) {
Candy.Core.setStropheStatus(status);
switch (status) {
case Strophe.Status.CONNECTED:
Candy.Core.log("[Connection] Connected");
Candy.Core.Action.Jabber.GetJidIfAnonymous();
/* falls through */
case Strophe.Status.ATTACHED:
Candy.Core.log("[Connection] Attached");
$(Candy).on("candy:core:roster:fetched", function() {
Candy.Core.Action.Jabber.Presence();
});
Candy.Core.Action.Jabber.Roster();
Candy.Core.Action.Jabber.EnableCarbons();
Candy.Core.Action.Jabber.Autojoin();
Candy.Core.Action.Jabber.GetIgnoreList();
break;
case Strophe.Status.DISCONNECTED:
Candy.Core.log("[Connection] Disconnected");
break;
case Strophe.Status.AUTHFAIL:
Candy.Core.log("[Connection] Authentication failed");
break;
case Strophe.Status.CONNECTING:
Candy.Core.log("[Connection] Connecting");
break;
case Strophe.Status.DISCONNECTING:
Candy.Core.log("[Connection] Disconnecting");
break;
case Strophe.Status.AUTHENTICATING:
Candy.Core.log("[Connection] Authenticating");
break;
case Strophe.Status.ERROR:
case Strophe.Status.CONNFAIL:
Candy.Core.log("[Connection] Failed (" + status + ")");
break;
default:
Candy.Core.warn("[Connection] Unknown status received:", status);
break;
}
/** Event: candy:core.chat.connection
* Connection status updates
*
* Parameters:
* (Strophe.Status) status - Strophe status
*/
$(Candy).triggerHandler("candy:core.chat.connection", {
status: status
});
}
};
/** Class: Candy.Core.Event.Jabber
* Jabber related events
*/
self.Jabber = {
/** Function: Version
* Responds to a version request
*
* Parameters:
* (String) msg - Raw XML Message
*
* Returns:
* (Boolean) - true
*/
Version: function(msg) {
Candy.Core.log("[Jabber] Version");
Candy.Core.Action.Jabber.Version($(msg));
return true;
},
/** Function: Presence
* Acts on a presence event
*
* Parameters:
* (String) msg - Raw XML Message
*
* Triggers:
* candy:core.presence using {from, stanza}
*
* Returns:
* (Boolean) - true
*/
Presence: function(msg) {
Candy.Core.log("[Jabber] Presence");
msg = $(msg);
if (msg.children('x[xmlns^="' + Strophe.NS.MUC + '"]').length > 0) {
if (msg.attr("type") === "error") {
self.Jabber.Room.PresenceError(msg);
} else {
self.Jabber.Room.Presence(msg);
}
} else {
/** Event: candy:core.presence
* Presence updates. Emitted only when not a muc presence.
*
* Parameters:
* (JID) from - From Jid
* (String) stanza - Stanza
*/
$(Candy).triggerHandler("candy:core.presence", {
from: msg.attr("from"),
stanza: msg
});
}
return true;
},
/** Function: RosterLoad
* Acts on the result of loading roster items from a cache
*
* Parameters:
* (String) items - List of roster items
*
* Triggers:
* candy:core.roster.loaded
*
* Returns:
* (Boolean) - true
*/
RosterLoad: function(items) {
self.Jabber._addRosterItems(items);
/** Event: candy:core.roster.loaded
* Notification of the roster having been loaded from cache
*/
$(Candy).triggerHandler("candy:core:roster:loaded", {
roster: Candy.Core.getRoster()
});
return true;
},
/** Function: RosterFetch
* Acts on the result of a roster fetch
*
* Parameters:
* (String) items - List of roster items
*
* Triggers:
* candy:core.roster.fetched
*
* Returns:
* (Boolean) - true
*/
RosterFetch: function(items) {
self.Jabber._addRosterItems(items);
/** Event: candy:core.roster.fetched
* Notification of the roster having been fetched
*/
$(Candy).triggerHandler("candy:core:roster:fetched", {
roster: Candy.Core.getRoster()
});
return true;
},
/** Function: RosterPush
* Acts on a roster push
*
* Parameters:
* (String) stanza - Raw XML Message
*
* Triggers:
* candy:core.roster.added
* candy:core.roster.updated
* candy:core.roster.removed
*
* Returns:
* (Boolean) - true
*/
RosterPush: function(items, updatedItem) {
if (!updatedItem) {
return true;
}
if (updatedItem.subscription === "remove") {
var contact = Candy.Core.getRoster().get(updatedItem.jid);
Candy.Core.getRoster().remove(updatedItem.jid);
/** Event: candy:core.roster.removed
* Notification of a roster entry having been removed
*
* Parameters:
* (Candy.Core.Contact) contact - The contact that was removed from the roster
*/
$(Candy).triggerHandler("candy:core:roster:removed", {
contact: contact
});
} else {
var user = Candy.Core.getRoster().get(updatedItem.jid);
if (!user) {
user = self.Jabber._addRosterItem(updatedItem);
/** Event: candy:core.roster.added
* Notification of a roster entry having been added
*
* Parameters:
* (Candy.Core.Contact) contact - The contact that was added
*/
$(Candy).triggerHandler("candy:core:roster:added", {
contact: user
});
} else {
/** Event: candy:core.roster.updated
* Notification of a roster entry having been updated
*
* Parameters:
* (Candy.Core.Contact) contact - The contact that was updated
*/
$(Candy).triggerHandler("candy:core:roster:updated", {
contact: user
});
}
}
return true;
},
_addRosterItem: function(item) {
var user = new Candy.Core.Contact(item);
Candy.Core.getRoster().add(user);
return user;
},
_addRosterItems: function(items) {
$.each(items, function(i, item) {
self.Jabber._addRosterItem(item);
});
},
/** Function: Bookmarks
* Acts on a bookmarks event. When a bookmark has the attribute autojoin set, joins this room.
*
* Parameters:
* (String) msg - Raw XML Message
*
* Returns:
* (Boolean) - true
*/
Bookmarks: function(msg) {
Candy.Core.log("[Jabber] Bookmarks");
// Autojoin bookmarks
$("conference", msg).each(function() {
var item = $(this);
if (item.attr("autojoin") && item.attr("autojoin") == "true") { // BAO Openfire has value true/false
Candy.Core.Action.Jabber.Room.Join(item.attr("jid"));
}
});
return true;
},
/** Function: PrivacyList
* Acts on a privacy list event and sets up the current privacy list of this user.
*
* If no privacy list has been added yet, create the privacy list and listen again to this event.
*
* Parameters:
* (String) msg - Raw XML Message
*
* Returns:
* (Boolean) - false to disable the handler after first call.
*/
PrivacyList: function(msg) {
Candy.Core.log("[Jabber] PrivacyList");
var currentUser = Candy.Core.getUser();
msg = $(msg);
if (msg.attr("type") === "result") {
$('list[name="ignore"] item', msg).each(function() {
var item = $(this);
if (item.attr("action") === "deny") {
currentUser.addToOrRemoveFromPrivacyList("ignore", item.attr("value"));
}
});
Candy.Core.Action.Jabber.SetIgnoreListActive();
return false;
}
return self.Jabber.PrivacyListError(msg);
},
/** Function: PrivacyListError
* Acts when a privacy list error has been received.
*
* Currently only handles the case, when a privacy list doesn't exist yet and creates one.
*
* Parameters:
* (String) msg - Raw XML Message
*
* Returns:
* (Boolean) - false to disable the handler after first call.
*/
PrivacyListError: function(msg) {
Candy.Core.log("[Jabber] PrivacyListError");
// check if msg says that privacyList doesn't exist
if ($('error[code="404"][type="cancel"] item-not-found', msg)) {
Candy.Core.Action.Jabber.ResetIgnoreList();
Candy.Core.Action.Jabber.SetIgnoreListActive();
}
return false;
},
/** Function: Message
* Acts on room, admin and server messages and notifies the view if required.
*
* Parameters:
* (String) msg - Raw XML Message
*
* Triggers:
* candy:core.chat.message.admin using {type, message}
* candy:core.chat.message.server {type, subject, message}
*
* Returns:
* (Boolean) - true
*/
Message: function(msg) {
Candy.Core.log("[Jabber] Message");
msg = $(msg);
var type = msg.attr("type") || "normal";
switch (type) {
case "normal":
var invite = self.Jabber._findInvite(msg);
if (invite) {
/** Event: candy:core:chat:invite
* Incoming chat invite for a MUC.
*
* Parameters:
* (String) roomJid - The room the invite is to
* (String) from - User JID that invite is from text
* (String) reason - Reason for invite
* (String) password - Password for the room
* (String) continuedThread - The thread ID if this is a continuation of a 1-on-1 chat
*/
$(Candy).triggerHandler("candy:core:chat:invite", invite);
}
/** Event: candy:core:chat:message:normal
* Messages with the type attribute of normal or those
* that do not have the optional type attribute.
*
* Parameters:
* (String) type - Type of the message
* (Object) message - Message object.
*/
$(Candy).triggerHandler("candy:core:chat:message:normal", {
type: type,
message: msg
});
break;
case "headline":
// Admin message
if (!msg.attr("to")) {
/** Event: candy:core.chat.message.admin
* Admin message
*
* Parameters:
* (String) type - Type of the message
* (String) message - Message text
*/
$(Candy).triggerHandler("candy:core.chat.message.admin", {
type: type,
message: msg.children("body").text()
});
} else {
/** Event: candy:core.chat.message.server
* Server message (e.g. subject)
*
* Parameters:
* (String) type - Message type
* (String) subject - Subject text
* (String) message - Message text
*/
$(Candy).triggerHandler("candy:core.chat.message.server", {
type: type,
subject: msg.children("subject").text(),
message: msg.children("body").text()
});
}
break;
case "groupchat":
case "chat":
case "error":
// Room message
self.Jabber.Room.Message(msg);
break;
default:
/** Event: candy:core:chat:message:other
* Messages with a type other than the ones listed in RFC3921
* section 2.1.1. This allows plugins to catch custom message
* types.
*
* Parameters:
* (String) type - Type of the message [default: message]
* (Object) message - Message object.
*/
// Detect message with type normal or with no type.
$(Candy).triggerHandler("candy:core:chat:message:other", {
type: type,
message: msg
});
}
return true;
},
_findInvite: function(msg) {
var mediatedInvite = msg.find("invite"), directInvite = msg.find('x[xmlns="jabber:x:conference"]'), invite;
if (mediatedInvite.length > 0) {
var passwordNode = msg.find("password"), password, reasonNode = mediatedInvite.find("reason"), reason, continueNode = mediatedInvite.find("continue");
if (passwordNode.text() !== "") {
password = passwordNode.text();
}
if (reasonNode.text() !== "") {
reason = reasonNode.text();
}
invite = {
roomJid: msg.attr("from"),
from: mediatedInvite.attr("from"),
reason: reason,
password: password,
continuedThread: continueNode.attr("thread")
};
}
if (directInvite.length > 0) {
invite = {
roomJid: directInvite.attr("jid"),
from: msg.attr("from"),
reason: directInvite.attr("reason"),
password: directInvite.attr("password"),
continuedThread: directInvite.attr("thread")
};
}
return invite;
},
/** Class: Candy.Core.Event.Jabber.Room
* Room specific events
*/
Room: {
/** Function: Disco
* Sets informations to rooms according to the disco info received.
*
* Parameters:
* (String) msg - Raw XML Message
*
* Returns:
* (Boolean) - true
*/
Disco: function(msg) {
Candy.Core.log("[Jabber:Room] Disco");
msg = $(msg);
// Temp fix for #219
// Don't go further if it's no conference disco reply
// FIXME: Do this in a more beautiful way
if (!msg.find('identity[category="conference"]').length) {
return true;
}
var roomJid = Strophe.getBareJidFromJid(Candy.Util.unescapeJid(msg.attr("from")));
// Client joined a room
if (!Candy.Core.getRooms()[roomJid]) {
Candy.Core.getRooms()[roomJid] = new Candy.Core.ChatRoom(roomJid);
}
// Room existed but room name was unknown
var identity = msg.find("identity");
if (identity.length) {
var roomName = identity.attr("name"), room = Candy.Core.getRoom(roomJid);
if (room.getName() === null) {
room.setName(Strophe.unescapeNode(roomName));
}
}
return true;
},
/** Function: Presence
* Acts on various presence messages (room leaving, room joining, error presence) and notifies view.
*
* Parameters:
* (Object) msg - jQuery object of XML message
*
* Triggers:
* candy:core.presence.room using {roomJid, roomName, user, action, currentUser}
*
* Returns:
* (Boolean) - true
*/
Presence: function(msg) {
Candy.Core.log("[Jabber:Room] Presence");
var from = Candy.Util.unescapeJid(msg.attr("from")), roomJid = Strophe.getBareJidFromJid(from), presenceType = msg.attr("type"), isNewRoom = self.Jabber.Room._msgHasStatusCode(msg, 201), nickAssign = self.Jabber.Room._msgHasStatusCode(msg, 210), nickChange = self.Jabber.Room._msgHasStatusCode(msg, 303);
// Current User joined a room
var room = Candy.Core.getRoom(roomJid);
if (!room) {
Candy.Core.getRooms()[roomJid] = new Candy.Core.ChatRoom(roomJid);
room = Candy.Core.getRoom(roomJid);
}
var roster = room.getRoster(), currentUser = room.getUser() ? room.getUser() : Candy.Core.getUser(), action, user, nick, show = msg.find("show"), item = msg.find("item");
// User joined a room
if (presenceType !== "unavailable") {
if (roster.get(from)) {
// role/affiliation change
user = roster.get(from);
var role = item.attr("role"), affiliation = item.attr("affiliation");
user.setRole(role);
user.setAffiliation(affiliation);
user.setStatus("available");
// FIXME: currently role/affilation changes are handled with this action
action = "join";
} else {
nick = Strophe.getResourceFromJid(from);
user = new Candy.Core.ChatUser(from, nick, item.attr("affiliation"), item.attr("role"), item.attr("jid"));
// Room existed but client (myself) is not yet registered
if (room.getUser() === null && (Candy.Core.getUser().getNick() === nick || nickAssign)) {
room.setUser(user);
currentUser = user;
}
user.setStatus("available");
roster.add(user);
action = "join";
}
if (show.length > 0) {
user.setStatus(show.text());
}
} else {
user = roster.get(from);
roster.remove(from);
if (nickChange) {
// user changed nick
nick = item.attr("nick");
action = "nickchange";
user.setPreviousNick(user.getNick());
user.setNick(nick);
user.setJid(Strophe.getBareJidFromJid(from) + "/" + nick);
roster.add(user);
} else {
action = "leave";
if (item.attr("role") === "none") {
if (self.Jabber.Room._msgHasStatusCode(msg, 307)) {
action = "kick";
} else if (self.Jabber.Room._msgHasStatusCode(msg, 301)) {
action = "ban";
}
}
if (Strophe.getResourceFromJid(from) === currentUser.getNick()) {
// Current User left a room
self.Jabber.Room._selfLeave(msg, from, roomJid, room.getName(), action);
return true;
}
}
}
/** Event: candy:core.presence.room
* Room presence updates
*
* Parameters:
* (String) roomJid - Room JID
* (String) roomName - Room name
* (Candy.Core.ChatUser) user - User which does the presence update
* (String) action - Action [kick, ban, leave, join]
* (Candy.Core.ChatUser) currentUser - Current local user
* (Boolean) isNewRoom - Whether the room is new (has just been created)
*/
$(Candy).triggerHandler("candy:core.presence.room", {
roomJid: roomJid,
roomName: room.getName(),
user: user,
action: action,
currentUser: currentUser,
isNewRoom: isNewRoom
});
return true;
},
_msgHasStatusCode: function(msg, code) {
return msg.find('status[code="' + code + '"]').length > 0;
},
_selfLeave: function(msg, from, roomJid, roomName, action) {
Candy.Core.log("[Jabber:Room] Leave");
Candy.Core.removeRoom(roomJid);
var item = msg.find("item"), reason, actor;
if (action === "kick" || action === "ban") {
reason = item.find("reason").text();
actor = item.find("actor").attr("jid");
}
var user = new Candy.Core.ChatUser(from, Strophe.getResourceFromJid(from), item.attr("affiliation"), item.attr("role"));
/** Event: candy:core.presence.leave
* When the local client leaves a room
*
* Also triggered when the local client gets kicked or banned from a room.
*
* Parameters:
* (String) roomJid - Room
* (String) roomName - Name of room
* (String) type - Presence type [kick, ban, leave]
* (String) reason - When type equals kick|ban, this is the reason the moderator has supplied.
* (String) actor - When type equals kick|ban, this is the moderator which did the kick
* (Candy.Core.ChatUser) user - user which leaves the room
*/
$(Candy).triggerHandler("candy:core.presence.leave", {
roomJid: roomJid,
roomName: roomName,
type: action,
reason: reason,
actor: actor,
user: user
});
},
/** Function: PresenceError
* Acts when a presence of type error has been retrieved.
*
* Parameters:
* (Object) msg - jQuery object of XML message
*
* Triggers:
* candy:core.presence.error using {msg, type, roomJid, roomName}
*
* Returns:
* (Boolean) - true
*/
PresenceError: function(msg) {
Candy.Core.log("[Jabber:Room] Presence Error");
var from = Candy.Util.unescapeJid(msg.attr("from")), roomJid = Strophe.getBareJidFromJid(from), room = Candy.Core.getRooms()[roomJid], roomName = room.getName();
// Presence error: Remove room from array to prevent error when disconnecting
Candy.Core.removeRoom(roomJid);
room = undefined;
/** Event: candy:core.presence.error
* Triggered when a presence error happened
*
* Parameters:
* (Object) msg - jQuery object of XML message
* (String) type - Error type
* (String) roomJid - Room jid
* (String) roomName - Room name
*/
$(Candy).triggerHandler("candy:core.presence.error", {
msg: msg,
type: msg.children("error").children()[0].tagName.toLowerCase(),
roomJid: roomJid,
roomName: roomName
});
return true;
},
/** Function: Message
* Acts on various message events (subject changed, private chat message, multi-user chat message)
* and notifies view.
*
* Parameters:
* (String) msg - jQuery object of XML message
*
* Triggers:
* candy:core.message using {roomJid, message, timestamp}
*
* Returns:
* (Boolean) - true
*/
Message: function(msg) {
Candy.Core.log("[Jabber:Room] Message");
var carbon = false, partnerJid = Candy.Util.unescapeJid(msg.attr("from"));
if (msg.children('sent[xmlns="' + Strophe.NS.CARBONS + '"]').length > 0) {
carbon = true;
msg = $(msg.children("sent").children("forwarded").children("message"));
partnerJid = Candy.Util.unescapeJid(msg.attr("to"));
}
if (msg.children('received[xmlns="' + Strophe.NS.CARBONS + '"]').length > 0) {
carbon = true;
msg = $(msg.children("received").children("forwarded").children("message"));
partnerJid = Candy.Util.unescapeJid(msg.attr("from"));
}
// Room subject
var roomJid, roomName, from, message, name, room, sender;
if (msg.children("subject").length > 0 && msg.children("subject").text().length > 0 && msg.attr("type") === "groupchat") {
roomJid = Candy.Util.unescapeJid(Strophe.getBareJidFromJid(partnerJid));
from = Candy.Util.unescapeJid(Strophe.getBareJidFromJid(msg.attr("from")));
roomName = Strophe.getNodeFromJid(roomJid);
message = {
from: from,
name: Strophe.getNodeFromJid(from),
body: msg.children("subject").text(),
type: "subject"
};
} else if (msg.attr("type") === "error") {
var error = msg.children("error");
if (error.children("text").length > 0) {
roomJid = partnerJid;
roomName = Strophe.getNodeFromJid(roomJid);
message = {
from: msg.attr("from"),
type: "info",
body: error.children("text").text()
};
}
} else if (msg.children("body").length > 0) {
// Private chat message
if (msg.attr("type") === "chat" || msg.attr("type") === "normal") {
from = Candy.Util.unescapeJid(msg.attr("from"));
var barePartner = Strophe.getBareJidFromJid(partnerJid), bareFrom = Strophe.getBareJidFromJid(from), isNoConferenceRoomJid = !Candy.Core.getRoom(barePartner);
if (isNoConferenceRoomJid) {
roomJid = barePartner;
var partner = Candy.Core.getRoster().get(barePartner);
if (partner) {
roomName = partner.getName();
} else {
roomName = Strophe.getNodeFromJid(barePartner);
}
if (bareFrom === Candy.Core.getUser().getJid()) {
sender = Candy.Core.getUser();
} else {
sender = Candy.Core.getRoster().get(bareFrom);
}
if (sender) {
name = sender.getName();
} else {
name = Strophe.getNodeFromJid(from);
}
} else {
roomJid = partnerJid;
room = Candy.Core.getRoom(Candy.Util.unescapeJid(Strophe.getBareJidFromJid(from)));
sender = room.getRoster().get(from);
if (sender) {
name = sender.getName();
} else {
name = Strophe.getResourceFromJid(from);
}
roomName = name;
}
message = {
from: from,
name: name,
body: msg.children("body").text(),
type: msg.attr("type"),
isNoConferenceRoomJid: isNoConferenceRoomJid
};
} else {
from = Candy.Util.unescapeJid(msg.attr("from"));
roomJid = Candy.Util.unescapeJid(Strophe.getBareJidFromJid(partnerJid));
var resource = Strophe.getResourceFromJid(partnerJid);
// Message from a user
if (resource) {
room = Candy.Core.getRoom(roomJid);
roomName = room.getName();
if (resource === Candy.Core.getUser().getNick()) {
sender = Candy.Core.getUser();
} else {
sender = room.getRoster().get(from);
}
if (sender) {
name = sender.getName();
} else {
name = Strophe.unescapeNode(resource);
}
message = {
from: roomJid,
name: name,
body: msg.children("body").text(),
type: msg.attr("type")
};
} else {
// we are not yet present in the room, let's just drop this message (issue #105)
if (!Candy.Core.getRooms()[partnerJid]) {
return true;
}
roomName = "";
message = {
from: roomJid,
name: "",
body: msg.children("body").text(),
type: "info"
};
}
}
var xhtmlChild = msg.children('html[xmlns="' + Strophe.NS.XHTML_IM + '"]');
if (xhtmlChild.length > 0) {
var xhtmlMessage = $($("<div>").append(xhtmlChild.children("body").first().contents()).html());
message.xhtmlMessage = xhtmlMessage;
}
self.Jabber.Room._checkForChatStateNotification(msg, roomJid, name);
} else {
return true;
}
// besides the delayed delivery (XEP-0203), there exists also XEP-0091 which is the legacy delayed delivery.
// the x[xmlns=jabber:x:delay] is the format in XEP-0091.
var delay = msg.children('delay[xmlns="' + Strophe.NS.DELAY + '"]');
message.delay = false;
// Default delay to being false.
if (delay.length < 1) {
// The jQuery xpath implementation doesn't support the or operator
delay = msg.children('x[xmlns="' + Strophe.NS.JABBER_DELAY + '"]');
} else {
// Add delay to the message object so that we can more easily tell if it's a delayed message or not.
message.delay = true;
}
var timestamp = delay.length > 0 ? delay.attr("stamp") : new Date().toISOString();
/** Event: candy:core.message
* Triggers on various message events (subject changed, private chat message, multi-user chat message).
*
* The resulting message object can contain different key-value pairs as stated in the documentation
* of the parameters itself.
*
* The following lists explain those parameters:
*
* Message Object Parameters:
* (String) from - The unmodified JID that the stanza came from
* (String) name - Sender name
* (String) body - Message text
* (String) type - Message type ([normal, chat, groupchat])
* or 'info' which is used internally for displaying informational messages
* (Boolean) isNoConferenceRoomJid - if a 3rd-party client sends a direct message to
* this user (not via the room) then the username is the node
* and not the resource.
* This flag tells if this is the case.
* (Boolean) delay - If there is a value for the delay element on a message it is a delayed message.
* This flag tells if this is the case.
*
* Parameters:
* (String) roomJid - Room jid. For one-on-one messages, this is sanitized to the bare JID for indexing purposes.
* (String) roomName - Name of the contact
* (Object) message - Depending on what kind of message, the object consists of different key-value pairs:
* - Room Subject: {name, body, type}
* - Error message: {type = 'info', body}
* - Private chat message: {name, body, type, isNoConferenceRoomJid}
* - MUC msg from a user: {name, body, type}
* - MUC msg from server: {name = '', body, type = 'info'}
* (String) timestamp - Timestamp, only when it's an offline message
* (Boolean) carbon - Indication of wether or not the message was a carbon
* (String) stanza - The raw XML stanza
*
* TODO:
* Streamline those events sent and rename the parameters.
*/
$(Candy).triggerHandler("candy:core.message", {
roomJid: roomJid,
roomName: roomName,
message: message,
timestamp: timestamp,
carbon: carbon,
stanza: msg
});
return true;
},
_checkForChatStateNotification: function(msg, roomJid, name) {
var chatStateElements = msg.children('*[xmlns="http://jabber.org/protocol/chatstates"]');
if (chatStateElements.length > 0) {
/** Event: candy:core:message:chatstate
* Triggers on any recieved chatstate notification.
*
* The resulting message object contains the name of the person, the roomJid, and the indicated chatstate.
*
* The following lists explain those parameters:
*
* Message Object Parameters:
* (String) name - User name
* (String) roomJid - Room jid
* (String) chatstate - Chatstate being indicated. ("active", "composing", "paused", "inactive", "gone")
*
*/
$(Candy).triggerHandler("candy:core:message:chatstate", {
name: name,
roomJid: roomJid,
chatstate: chatStateElements[0].tagName
});
}
}
}
};
return self;
}(Candy.Core.Event || {}, Strophe, jQuery);
/** File: observer.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Strophe, Mustache, jQuery */
/** Class: Candy.View.Observer
* Observes Candy core events
*
* Parameters:
* (Candy.View.Observer) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Observer = function(self, $) {
/** PrivateVariable: _showConnectedMessageModal
* Ugly way to determine if the 'connected' modal should be shown.
* Is set to false in case no autojoin param is set.
*/
var _showConnectedMessageModal = true;
/** Class: Candy.View.Observer.Chat
* Chat events
*/
self.Chat = {
/** Function: Connection
* The update method gets called whenever an event to which "Chat" is subscribed.
*
* Currently listens for connection status updates
*
* Parameters:
* (jQuery.Event) event - jQuery Event object
* (Object) args - {status (Strophe.Status.*)}
*/
Connection: function(event, args) {
var eventName = "candy:view.connection.status-" + args.status;
/** Event: candy:view.connection.status-<STROPHE-STATUS>
* Using this event, you can alter the default Candy (View) behaviour when reacting
* to connection updates.
*
* STROPHE-STATUS has to be replaced by one of <Strophe.Status at https://github.com/strophe/strophejs/blob/master/src/core.js#L276>:
* - ERROR: 0,
* - CONNECTING: 1,
* - CONNFAIL: 2,
* - AUTHENTICATING: 3,
* - AUTHFAIL: 4,
* - CONNECTED: 5,
* - DISCONNECTED: 6,
* - DISCONNECTING: 7,
* - ATTACHED: 8
*
*
* If your event handler returns `false`, no View changes will take place.
* You can, of course, also return `true` and do custom things but still
* let Candy (View) do it's job.
*
* This event has been implemented due to <issue #202 at https://github.com/candy-chat/candy/issues/202>
* and here's an example use-case for it:
*
* (start code)
* // react to DISCONNECTED event
* $(Candy).on('candy:view.connection.status-6', function() {
* // on next browser event loop
* setTimeout(function() {
* // reload page to automatically reattach on disconnect
* window.location.reload();
* }, 0);
* // stop view changes right here.
* return false;
* });
* (end code)
*/
if ($(Candy).triggerHandler(eventName) === false) {
return false;
}
switch (args.status) {
case Strophe.Status.CONNECTING:
case Strophe.Status.AUTHENTICATING:
Candy.View.Pane.Chat.Modal.show($.i18n._("statusConnecting"), false, true);
break;
case Strophe.Status.ATTACHED:
case Strophe.Status.CONNECTED:
if (_showConnectedMessageModal === true) {
// only show 'connected' if the autojoin error is not shown
// which is determined by having a visible modal in this stage.
Candy.View.Pane.Chat.Modal.show($.i18n._("statusConnected"));
Candy.View.Pane.Chat.Modal.hide();
}
break;
case Strophe.Status.DISCONNECTING:
Candy.View.Pane.Chat.Modal.show($.i18n._("statusDisconnecting"), false, true);
break;
case Strophe.Status.DISCONNECTED:
var presetJid = Candy.Core.isAnonymousConnection() ? Strophe.getDomainFromJid(Candy.Core.getUser().getJid()) : null;
Candy.View.Pane.Chat.Modal.showLoginForm($.i18n._("statusDisconnected"), presetJid);
break;
case Strophe.Status.AUTHFAIL:
Candy.View.Pane.Chat.Modal.showLoginForm($.i18n._("statusAuthfail"));
break;
default:
Candy.View.Pane.Chat.Modal.show($.i18n._("status", args.status));
break;
}
},
/** Function: Message
* Dispatches admin and info messages
*
* Parameters:
* (jQuery.Event) event - jQuery Event object
* (Object) args - {type (message/chat/groupchat), subject (if type = message), message}
*/
Message: function(event, args) {
if (args.type === "message") {
Candy.View.Pane.Chat.adminMessage(args.subject || "", args.message);
} else if (args.type === "chat" || args.type === "groupchat") {
// use onInfoMessage as infos from the server shouldn't be hidden by the infoMessage switch.
Candy.View.Pane.Chat.onInfoMessage(Candy.View.getCurrent().roomJid, args.subject || "", args.message);
}
}
};
/** Class: Candy.View.Observer.Presence
* Presence update events
*/
self.Presence = {
/** Function: update
* Every presence update gets dispatched from this method.
*
* Parameters:
* (jQuery.Event) event - jQuery.Event object
* (Object) args - Arguments differ on each type
*
* Uses:
* - <notifyPrivateChats>
*/
update: function(event, args) {
// Client left
if (args.type === "leave") {
var user = Candy.View.Pane.Room.getUser(args.roomJid);
Candy.View.Pane.Room.close(args.roomJid);
self.Presence.notifyPrivateChats(user, args.type);
} else if (args.type === "kick" || args.type === "ban") {
var actorName = args.actor ? Strophe.getNodeFromJid(args.actor) : null, actionLabel, translationParams = [ args.roomName ];
if (actorName) {
translationParams.push(actorName);
}
switch (args.type) {
case "kick":
actionLabel = $.i18n._(actorName ? "youHaveBeenKickedBy" : "youHaveBeenKicked", translationParams);
break;
case "ban":
actionLabel = $.i18n._(actorName ? "youHaveBeenBannedBy" : "youHaveBeenBanned", translationParams);
break;
}
Candy.View.Pane.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.adminMessageReason, {
reason: args.reason,
_action: actionLabel,
_reason: $.i18n._("reasonWas", [ args.reason ])
}));
setTimeout(function() {
Candy.View.Pane.Chat.Modal.hide(function() {
Candy.View.Pane.Room.close(args.roomJid);
self.Presence.notifyPrivateChats(args.user, args.type);
});
}, 5e3);
var evtData = {
type: args.type,
reason: args.reason,
roomJid: args.roomJid,
user: args.user
};
/** Event: candy:view.presence
* Presence update when kicked or banned
*
* Parameters:
* (String) type - Presence type [kick, ban]
* (String) reason - Reason for the kick|ban [optional]
* (String) roomJid - Room JID
* (Candy.Core.ChatUser) user - User which has been kicked or banned
*/
$(Candy).triggerHandler("candy:view.presence", [ evtData ]);
} else if (args.roomJid) {
args.roomJid = Candy.Util.unescapeJid(args.roomJid);
// Initialize room if not yet existing
if (!Candy.View.Pane.Chat.rooms[args.roomJid]) {
if (Candy.View.Pane.Room.init(args.roomJid, args.roomName) === false) {
return false;
}
Candy.View.Pane.Room.show(args.roomJid);
}
Candy.View.Pane.Roster.update(args.roomJid, args.user, args.action, args.currentUser);
// Notify private user chats if existing, but not in case the action is nickchange
// -- this is because the nickchange presence already contains the new
// user jid
if (Candy.View.Pane.Chat.rooms[args.user.getJid()] && args.action !== "nickchange") {
Candy.View.Pane.Roster.update(args.user.getJid(), args.user, args.action, args.currentUser);
Candy.View.Pane.PrivateRoom.setStatus(args.user.getJid(), args.action);
}
} else {
// Presence for a one-on-one chat
var bareJid = Strophe.getBareJidFromJid(args.from), room = Candy.View.Pane.Chat.rooms[bareJid];
if (!room) {
return false;
}
room.targetJid = bareJid;
}
},
/** Function: notifyPrivateChats
* Notify private user chats if existing
*
* Parameters:
* (Candy.Core.ChatUser) user - User which has done the event
* (String) type - Event type (leave, join, kick/ban)
*/
notifyPrivateChats: function(user, type) {
Candy.Core.log("[View:Observer] notify Private Chats");
var roomJid;
for (roomJid in Candy.View.Pane.Chat.rooms) {
if (Candy.View.Pane.Chat.rooms.hasOwnProperty(roomJid) && Candy.View.Pane.Room.getUser(roomJid) && user.getJid() === Candy.View.Pane.Room.getUser(roomJid).getJid()) {
Candy.View.Pane.Roster.update(roomJid, user, type, user);
Candy.View.Pane.PrivateRoom.setStatus(roomJid, type);
}
}
}
};
/** Function: Candy.View.Observer.PresenceError
* Presence errors get handled in this method
*
* Parameters:
* (jQuery.Event) event - jQuery.Event object
* (Object) args - {msg, type, roomJid, roomName}
*/
self.PresenceError = function(obj, args) {
switch (args.type) {
case "not-authorized":
var message;
if (args.msg.children("x").children("password").length > 0) {
message = $.i18n._("passwordEnteredInvalid", [ args.roomName ]);
}
Candy.View.Pane.Chat.Modal.showEnterPasswordForm(args.roomJid, args.roomName, message);
break;
case "conflict":
Candy.View.Pane.Chat.Modal.showNicknameConflictForm(args.roomJid);
break;
case "registration-required":
Candy.View.Pane.Chat.Modal.showError("errorMembersOnly", [ args.roomName ]);
break;
case "service-unavailable":
Candy.View.Pane.Chat.Modal.showError("errorMaxOccupantsReached", [ args.roomName ]);
break;
}
};
/** Function: Candy.View.Observer.Message
* Messages received get dispatched from this method.
*
* Parameters:
* (jQuery.Event) event - jQuery Event object
* (Object) args - {message, roomJid}
*/
self.Message = function(event, args) {
if (args.message.type === "subject") {
if (!Candy.View.Pane.Chat.rooms[args.roomJid]) {
Candy.View.Pane.Room.init(args.roomJid, args.roomName);
Candy.View.Pane.Room.show(args.roomJid);
}
Candy.View.Pane.Room.setSubject(args.roomJid, args.message.body);
} else if (args.message.type === "info") {
Candy.View.Pane.Chat.infoMessage(args.roomJid, null, args.message.body);
} else {
// Initialize room if it's a message for a new private user chat
if (args.message.type === "chat" && !Candy.View.Pane.Chat.rooms[args.roomJid]) {
Candy.View.Pane.PrivateRoom.open(args.roomJid, args.roomName, false, args.message.isNoConferenceRoomJid);
}
var room = Candy.View.Pane.Chat.rooms[args.roomJid];
if (room.targetJid === args.roomJid && !args.carbon) {
// No messages yet received. Lock the room to this resource.
room.targetJid = args.message.from;
} else if (room.targetJid === args.message.from) {} else {
// Message received from alternative resource. Release the resource lock.
room.targetJid = args.roomJid;
}
Candy.View.Pane.Message.show(args.roomJid, args.message.name, args.message.body, args.message.xhtmlMessage, args.timestamp, args.message.from, args.carbon, args.stanza);
}
};
/** Function: Candy.View.Observer.Login
* The login event gets dispatched to this method
*
* Parameters:
* (jQuery.Event) event - jQuery Event object
* (Object) args - {presetJid}
*/
self.Login = function(event, args) {
Candy.View.Pane.Chat.Modal.showLoginForm(null, args.presetJid);
};
/** Class: Candy.View.Observer.AutojoinMissing
* Displays an error about missing autojoin information
*/
self.AutojoinMissing = function() {
_showConnectedMessageModal = false;
Candy.View.Pane.Chat.Modal.showError("errorAutojoinMissing");
};
return self;
}(Candy.View.Observer || {}, jQuery);
/** File: chat.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, document, Mustache, Strophe, Audio, jQuery */
/** Class: Candy.View.Pane
* Candy view pane handles everything regarding DOM updates etc.
*
* Parameters:
* (Candy.View.Pane) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Pane = function(self, $) {
/** Class: Candy.View.Pane.Chat
* Chat-View related view updates
*/
self.Chat = {
/** Variable: rooms
* Contains opened room elements
*/
rooms: [],
/** Function: addTab
* Add a tab to the chat pane.
*
* Parameters:
* (String) roomJid - JID of room
* (String) roomName - Tab label
* (String) roomType - Type of room: `groupchat` or `chat`
*/
addTab: function(roomJid, roomName, roomType) {
var roomId = Candy.Util.jidToId(roomJid);
var evtData = {
roomJid: roomJid,
roomName: roomName,
roomType: roomType,
roomId: roomId
};
/** Event: candy:view.pane.before-tab
* Before sending a message
*
* Parameters:
* (String) roomJid - JID of the room the tab is for.
* (String) roomName - Name of the room.
* (String) roomType - What type of room: `groupchat` or `chat`
*
* Returns:
* Boolean|undefined - If you want to handle displaying the tab on your own, return false.
*/
if ($(Candy).triggerHandler("candy:view.pane.before-tab", evtData) === false) {
event.preventDefault();
return;
}
var roomname = roomName || Strophe.getNodeFromJid(roomJid); // BAO
if (roomname.indexOf("workgroup-") == 0) roomname = roomname.substring(10);
var html = Mustache.to_html(Candy.View.Template.Chat.tab, {
roomJid: roomJid,
roomId: roomId,
name: roomname,
privateUserChat: function() {
return roomType === "chat";
},
roomType: roomType
}), tab = $(html).appendTo("#chat-tabs");
tab.click(self.Chat.tabClick);
// TODO: maybe we find a better way to get the close element.
$("a.close", tab).click(self.Chat.tabClose);
self.Chat.fitTabs();
},
/** Function: getTab
* Get tab by JID.
*
* Parameters:
* (String) roomJid - JID of room
*
* Returns:
* (jQuery object) - Tab element
*/
getTab: function(roomJid) {
return $("#chat-tabs").children('li[data-roomjid="' + roomJid + '"]');
},
/** Function: removeTab
* Remove tab element.
*
* Parameters:
* (String) roomJid - JID of room
*/
removeTab: function(roomJid) {
self.Chat.getTab(roomJid).remove();
self.Chat.fitTabs();
},
/** Function: setActiveTab
* Set the active tab.
*
* Add CSS classname `active` to the choosen tab and remove `active` from all other.
*
* Parameters:
* (String) roomJid - JID of room
*/
setActiveTab: function(roomJid) {
$("#chat-tabs").children().each(function() {
var tab = $(this);
if (tab.attr("data-roomjid") === roomJid) {
tab.addClass("active");
} else {
tab.removeClass("active");
}
});
},
/** Function: increaseUnreadMessages
* Increase unread message count in a tab by one.
*
* Parameters:
* (String) roomJid - JID of room
*
* Uses:
* - <Window.increaseUnreadMessages>
*/
increaseUnreadMessages: function(roomJid) {
var unreadElem = this.getTab(roomJid).find(".unread");
unreadElem.show().text(unreadElem.text() !== "" ? parseInt(unreadElem.text(), 10) + 1 : 1);
// only increase window unread messages in private chats
if (self.Chat.rooms[roomJid].type === "chat" || Candy.View.getOptions().updateWindowOnAllMessages === true) {
self.Window.increaseUnreadMessages();
}
},
/** Function: clearUnreadMessages
* Clear unread message count in a tab.
*
* Parameters:
* (String) roomJid - JID of room
*
* Uses:
* - <Window.reduceUnreadMessages>
*/
clearUnreadMessages: function(roomJid) {
var unreadElem = self.Chat.getTab(roomJid).find(".unread");
self.Window.reduceUnreadMessages(unreadElem.text());
unreadElem.hide().text("");
},
/** Function: tabClick
* Tab click event: show the room associated with the tab and stops the event from doing the default.
*/
tabClick: function(e) {
// remember scroll position of current room
var currentRoomJid = Candy.View.getCurrent().roomJid;
var roomPane = self.Room.getPane(currentRoomJid, ".message-pane");
if (roomPane) {
self.Chat.rooms[currentRoomJid].scrollPosition = roomPane.scrollTop();
}
self.Room.show($(this).attr("data-roomjid"));
e.preventDefault();
},
/** Function: tabClose
* Tab close (click) event: Leave the room (groupchat) or simply close the tab (chat).
*
* Parameters:
* (DOMEvent) e - Event triggered
*
* Returns:
* (Boolean) - false, this will stop the event from bubbling
*/
tabClose: function() {
var roomJid = $(this).parent().attr("data-roomjid");
// close private user tab
if (self.Chat.rooms[roomJid].type === "chat") {
self.Room.close(roomJid);
} else {
Candy.Core.Action.Jabber.Room.Leave(roomJid);
}
return false;
},
/** Function: allTabsClosed
* All tabs closed event: Disconnect from service. Hide sound control.
*
* TODO: Handle window close
*
* Returns:
* (Boolean) - false, this will stop the event from bubbling
*/
allTabsClosed: function() {
if (Candy.Core.getOptions().disconnectWithoutTabs) {
Candy.Core.disconnect();
self.Chat.Toolbar.hide();
self.Chat.hideMobileIcon();
return;
}
},
/** Function: fitTabs
* Fit tab size according to window size
*/
fitTabs: function() {
var availableWidth = $("#chat-tabs").innerWidth(), tabsWidth = 0, tabs = $("#chat-tabs").children();
tabs.each(function() {
tabsWidth += $(this).css({
width: "auto",
overflow: "visible"
}).outerWidth(true);
});
if (tabsWidth > availableWidth) {
// tabs.[outer]Width() measures the first element in `tabs`. It's no very readable but nearly two times faster than using :first
var tabDiffToRealWidth = tabs.outerWidth(true) - tabs.width(), tabWidth = Math.floor(availableWidth / tabs.length) - tabDiffToRealWidth;
tabs.css({
width: tabWidth,
overflow: "hidden"
});
}
},
/** Function: hideMobileIcon
* Hide mobile roster pane icon.
*/
hideMobileIcon: function() {
$("#mobile-roster-icon").hide();
},
/** Function: showMobileIcon
* Show mobile roster pane icon.
*/
showMobileIcon: function() {
$("#mobile-roster-icon").show();
},
/** Function: clickMobileIcon
* Add class to 'open' roster pane (on mobile).
*/
clickMobileIcon: function(e) {
if ($(".room-pane").is(".open")) {
$(".room-pane").removeClass("open");
} else {
$(".room-pane").addClass("open");
}
e.preventDefault();
},
/** Function: adminMessage
* Display admin message
*
* Parameters:
* (String) subject - Admin message subject
* (String) message - Message to be displayed
*
* Triggers:
* candy:view.chat.admin-message using {subject, message}
*/
adminMessage: function(subject, message) {
if (Candy.View.getCurrent().roomJid) {
// Simply dismiss admin message if no room joined so far. TODO: maybe we should show those messages on a dedicated pane?
message = Candy.Util.Parser.all(message.substring(0, Candy.View.getOptions().crop.message.body));
if (Candy.View.getOptions().enableXHTML === true) {
message = Candy.Util.parseAndCropXhtml(message, Candy.View.getOptions().crop.message.body);
}
var timestamp = new Date();
var html = Mustache.to_html(Candy.View.Template.Chat.adminMessage, {
subject: subject,
message: message,
sender: $.i18n._("administratorMessageSubject"),
time: Candy.Util.localizedTime(timestamp),
timestamp: timestamp.toISOString()
});
$("#chat-rooms").children().each(function() {
self.Room.appendToMessagePane($(this).attr("data-roomjid"), html);
});
self.Room.scrollToBottom(Candy.View.getCurrent().roomJid);
/** Event: candy:view.chat.admin-message
* After admin message display
*
* Parameters:
* (String) presetJid - Preset user JID
*/
$(Candy).triggerHandler("candy:view.chat.admin-message", {
subject: subject,
message: message
});
}
},
/** Function: infoMessage
* Display info message. This is a wrapper for <onInfoMessage> to be able to disable certain info messages.
*
* Parameters:
* (String) roomJid - Room JID
* (String) subject - Subject
* (String) message - Message
*/
infoMessage: function(roomJid, subject, message) {
self.Chat.onInfoMessage(roomJid, subject, message);
},
/** Function: onInfoMessage
* Display info message. Used by <infoMessage> and several other functions which do not wish that their info message
* can be disabled (such as kick/ban message or leave/join message in private chats).
*
* Parameters:
* (String) roomJid - Room JID
* (String) subject - Subject
* (String) message - Message
*/
onInfoMessage: function(roomJid, subject, message) {
message = message || "";
if (Candy.View.getCurrent().roomJid && self.Chat.rooms[roomJid]) {
// Simply dismiss info message if no room joined so far. TODO: maybe we should show those messages on a dedicated pane?
if (Candy.View.getOptions().enableXHTML === true && message.length > 0) {
message = Candy.Util.parseAndCropXhtml(message, Candy.View.getOptions().crop.message.body);
} else {
message = Candy.Util.Parser.all(message.substring(0, Candy.View.getOptions().crop.message.body));
}
var timestamp = new Date();
var html = Mustache.to_html(Candy.View.Template.Chat.infoMessage, {
subject: subject,
message: $.i18n._(message),
time: Candy.Util.localizedTime(timestamp),
timestamp: timestamp.toISOString()
});
self.Room.appendToMessagePane(roomJid, html);
if (Candy.View.getCurrent().roomJid === roomJid) {
self.Room.scrollToBottom(Candy.View.getCurrent().roomJid);
}
}
},
/** Class: Candy.View.Pane.Toolbar
* Chat toolbar for things like emoticons toolbar, room management etc.
*/
Toolbar: {
_supportsNativeAudio: null,
/** Function: init
* Register handler and enable or disable sound and status messages.
*/
init: function() {
$("#emoticons-icon").click(function(e) {
self.Chat.Context.showEmoticonsMenu(e.currentTarget);
e.stopPropagation();
});
$("#chat-autoscroll-control").click(self.Chat.Toolbar.onAutoscrollControlClick);
try {
if (!!document.createElement("audio").canPlayType) {
var a = document.createElement("audio");
if (!!a.canPlayType("audio/mpeg;").replace(/no/, "")) {
self.Chat.Toolbar._supportsNativeAudio = "mp3";
} else if (!!a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, "")) {
self.Chat.Toolbar._supportsNativeAudio = "ogg";
} else if (!!a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, "")) {
self.Chat.Toolbar._supportsNativeAudio = "m4a";
}
}
} catch (e) {}
$("#chat-sound-control").click(self.Chat.Toolbar.onSoundControlClick);
if (Candy.Util.cookieExists("candy-nosound")) {
$("#chat-sound-control").click();
}
$("#chat-statusmessage-control").click(self.Chat.Toolbar.onStatusMessageControlClick);
if (Candy.Util.cookieExists("candy-nostatusmessages")) {
$("#chat-statusmessage-control").click();
}
$(".box-shadow-icon").click(self.Chat.clickMobileIcon);
},
/** Function: show
* Show toolbar.
*/
show: function() {
$("#chat-toolbar").show();
},
/** Function: hide
* Hide toolbar.
*/
hide: function() {
$("#chat-toolbar").hide();
},
/* Function: update
* Update toolbar for specific room
*/
update: function(roomJid) {
var context = $("#chat-toolbar").find(".context"), me = self.Room.getUser(roomJid);
if (!me || !me.isModerator()) {
context.hide();
} else {
context.show().click(function(e) {
self.Chat.Context.show(e.currentTarget, roomJid);
e.stopPropagation();
});
}
self.Chat.Toolbar.updateUsercount(self.Chat.rooms[roomJid].usercount);
},
/** Function: playSound
* Play sound (default method).
*/
playSound: function() {
self.Chat.Toolbar.onPlaySound();
},
/** Function: onPlaySound
* Sound play event handler. Uses native (HTML5) audio if supported,
* otherwise it will attempt to use bgsound with autostart.
*
* Don't call this method directly. Call `playSound()` instead.
* `playSound()` will only call this method if sound is enabled.
*/
onPlaySound: function() {
try {
if (self.Chat.Toolbar._supportsNativeAudio !== null) {
new Audio(Candy.View.getOptions().assets + "notify." + self.Chat.Toolbar._supportsNativeAudio).play();
} else {
$("#chat-sound-control bgsound").remove();
$("<bgsound/>").attr({
src: Candy.View.getOptions().assets + "notify.mp3",
loop: 1,
autostart: true
}).appendTo("#chat-sound-control");
}
} catch (e) {}
},
/** Function: onSoundControlClick
* Sound control click event handler.
*
* Toggle sound (overwrite `playSound()`) and handle cookies.
*/
onSoundControlClick: function() {
var control = $("#chat-sound-control");
if (control.hasClass("checked")) {
self.Chat.Toolbar.playSound = function() {};
Candy.Util.setCookie("candy-nosound", "1", 365);
} else {
self.Chat.Toolbar.playSound = function() {
self.Chat.Toolbar.onPlaySound();
};
Candy.Util.deleteCookie("candy-nosound");
}
control.toggleClass("checked");
},
/** Function: onAutoscrollControlClick
* Autoscroll control event handler.
*
* Toggle autoscroll
*/
onAutoscrollControlClick: function() {
var control = $("#chat-autoscroll-control");
if (control.hasClass("checked")) {
self.Room.scrollToBottom = function(roomJid) {
self.Room.onScrollToStoredPosition(roomJid);
};
self.Window.autoscroll = false;
} else {
self.Room.scrollToBottom = function(roomJid) {
self.Room.onScrollToBottom(roomJid);
};
self.Room.scrollToBottom(Candy.View.getCurrent().roomJid);
self.Window.autoscroll = true;
}
control.toggleClass("checked");
},
/** Function: onStatusMessageControlClick
* Status message control event handler.
*
* Toggle status message
*/
onStatusMessageControlClick: function() {
var control = $("#chat-statusmessage-control");
if (control.hasClass("checked")) {
self.Chat.infoMessage = function() {};
Candy.Util.setCookie("candy-nostatusmessages", "1", 365);
} else {
self.Chat.infoMessage = function(roomJid, subject, message) {
self.Chat.onInfoMessage(roomJid, subject, message);
};
Candy.Util.deleteCookie("candy-nostatusmessages");
}
control.toggleClass("checked");
},
/** Function: updateUserCount
* Update usercount element with count.
*
* Parameters:
* (Integer) count - Current usercount
*/
updateUsercount: function(count) {
$("#chat-usercount").text(count);
}
},
/** Class: Candy.View.Pane.Modal
* Modal window
*/
Modal: {
/** Function: show
* Display modal window
*
* Parameters:
* (String) html - HTML code to put into the modal window
* (Boolean) showCloseControl - set to true if a close button should be displayed [default false]
* (Boolean) showSpinner - set to true if a loading spinner should be shown [default false]
* (String) modalClass - custom class (or space-separate classes) to attach to the modal
*/
show: function(html, showCloseControl, showSpinner, modalClass) {
if (showCloseControl) {
self.Chat.Modal.showCloseControl();
} else {
self.Chat.Modal.hideCloseControl();
}
if (showSpinner) {
self.Chat.Modal.showSpinner();
} else {
self.Chat.Modal.hideSpinner();
}
// Reset classes to 'modal-common' only in case .show() is called
// with different arguments before .hide() can remove the last applied
// custom class
$("#chat-modal").removeClass().addClass("modal-common");
if (modalClass) {
$("#chat-modal").addClass(modalClass);
}
$("#chat-modal").stop(false, true);
$("#chat-modal-body").html(html);
$("#chat-modal").fadeIn("fast");
$("#chat-modal-overlay").show();
},
/** Function: hide
* Hide modal window
*
* Parameters:
* (Function) callback - Calls the specified function after modal window has been hidden.
*/
hide: function(callback) {
// Reset classes to include only `modal-common`.
$("#chat-modal").removeClass().addClass("modal-common");
$("#chat-modal").fadeOut("fast", function() {
$("#chat-modal-body").text("");
$("#chat-modal-overlay").hide();
});
// restore initial esc handling
$(document).keydown(function(e) {
if (e.which === 27) {
e.preventDefault();
}
});
if (callback) {
callback();
}
},
/** Function: showSpinner
* Show loading spinner
*/
showSpinner: function() {
$("#chat-modal-spinner").show();
},
/** Function: hideSpinner
* Hide loading spinner
*/
hideSpinner: function() {
$("#chat-modal-spinner").hide();
},
/** Function: showCloseControl
* Show a close button
*/
showCloseControl: function() {
$("#admin-message-cancel").show().click(function(e) {
self.Chat.Modal.hide();
// some strange behaviour on IE7 (and maybe other browsers) triggers onWindowUnload when clicking on the close button.
// prevent this.
e.preventDefault();
});
// enable esc to close modal
$(document).keydown(function(e) {
if (e.which === 27) {
self.Chat.Modal.hide();
e.preventDefault();
}
});
},
/** Function: hideCloseControl
* Hide the close button
*/
hideCloseControl: function() {
$("#admin-message-cancel").hide().click(function() {});
},
/** Function: showLoginForm
* Show the login form modal
*
* Parameters:
* (String) message - optional message to display above the form
* (String) presetJid - optional user jid. if set, the user will only be prompted for password.
*/
showLoginForm: function(message, presetJid) {
var domains = Candy.Core.getOptions().domains;
var hideDomainList = Candy.Core.getOptions().hideDomainList;
domains = domains ? domains.map(function(d) {
return {
domain: d
};
}) : null;
var customClass = domains && !hideDomainList ? "login-with-domains" : null;
self.Chat.Modal.show((message ? message : "") + Mustache.to_html(Candy.View.Template.Login.form, {
_labelNickname: $.i18n._("labelNickname"),
_labelUsername: $.i18n._("labelUsername"),
domains: domains,
_labelPassword: $.i18n._("labelPassword"),
_loginSubmit: $.i18n._("loginSubmit"),
displayPassword: !Candy.Core.isAnonymousConnection(),
displayUsername: !presetJid,
displayDomain: domains ? true : false,
displayNickname: Candy.Core.isAnonymousConnection(),
presetJid: presetJid ? presetJid : false
}), null, null, customClass);
if (hideDomainList) {
$("#domain").hide();
$(".at-symbol").hide();
}
$("#login-form").children(":input:first").focus();
// register submit handler
$("#login-form").submit(function() {
var username = $("#username").val(), password = $("#password").val(), domain = $("#domain");
domain = domain.length ? domain.val().split(" ")[0] : null;
if (!Candy.Core.isAnonymousConnection()) {
var jid;
if (domain) {
// domain is stipulated
// Ensure there is no domain part in username
username = username.split("@")[0];
jid = username + "@" + domain;
} else {
// domain not stipulated
// guess the input and create a jid out of it
jid = Candy.Core.getUser() && username.indexOf("@") < 0 ? username + "@" + Strophe.getDomainFromJid(Candy.Core.getUser().getJid()) : username;
}
if (jid.indexOf("@") < 0 && !Candy.Core.getUser()) {
Candy.View.Pane.Chat.Modal.showLoginForm($.i18n._("loginInvalid"));
} else {
//Candy.View.Pane.Chat.Modal.hide();
Candy.Core.connect(jid, password);
}
} else {
// anonymous login
Candy.Core.connect(presetJid, null, username);
}
return false;
});
},
/** Function: showEnterPasswordForm
* Shows a form for entering room password
*
* Parameters:
* (String) roomJid - Room jid to join
* (String) roomName - Room name
* (String) message - [optional] Message to show as the label
*/
showEnterPasswordForm: function(roomJid, roomName, message) {
self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.PresenceError.enterPasswordForm, {
roomName: roomName,
_labelPassword: $.i18n._("labelPassword"),
_label: message ? message : $.i18n._("enterRoomPassword", [ roomName ]),
_joinSubmit: $.i18n._("enterRoomPasswordSubmit")
}), true);
$("#password").focus();
// register submit handler
$("#enter-password-form").submit(function() {
var password = $("#password").val();
self.Chat.Modal.hide(function() {
Candy.Core.Action.Jabber.Room.Join(roomJid, password);
});
return false;
});
},
/** Function: showNicknameConflictForm
* Shows a form indicating that the nickname is already taken and
* for chosing a new nickname
*
* Parameters:
* (String) roomJid - Room jid to join
*/
showNicknameConflictForm: function(roomJid) {
self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.PresenceError.nicknameConflictForm, {
_labelNickname: $.i18n._("labelNickname"),
_label: $.i18n._("nicknameConflict"),
_loginSubmit: $.i18n._("loginSubmit")
}));
$("#nickname").focus();
// register submit handler
$("#nickname-conflict-form").submit(function() {
var nickname = $("#nickname").val();
self.Chat.Modal.hide(function() {
Candy.Core.getUser().data.nick = nickname;
Candy.Core.Action.Jabber.Room.Join(roomJid);
});
return false;
});
},
/** Function: showError
* Show modal containing error message
*
* Parameters:
* (String) message - key of translation to display
* (Array) replacements - array containing replacements for translation (%s)
*/
showError: function(message, replacements) {
self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.PresenceError.displayError, {
_error: $.i18n._(message, replacements)
}), true);
}
},
/** Class: Candy.View.Pane.Tooltip
* Class to display tooltips over specific elements
*/
Tooltip: {
/** Function: show
* Show a tooltip on event.currentTarget with content specified or content within the target's attribute data-tooltip.
*
* On mouseleave on the target, hide the tooltip.
*
* Parameters:
* (Event) event - Triggered event
* (String) content - Content to display [optional]
*/
show: function(event, content) {
var tooltip = $("#tooltip"), target = $(event.currentTarget);
if (!content) {
content = target.attr("data-tooltip");
}
if (tooltip.length === 0) {
var html = Mustache.to_html(Candy.View.Template.Chat.tooltip);
$("#chat-pane").append(html);
tooltip = $("#tooltip");
}
$("#context-menu").hide();
tooltip.stop(false, true);
tooltip.children("div").html(content);
var pos = target.offset(), posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(tooltip, pos.left), posTop = Candy.Util.getPosTopAccordingToWindowBounds(tooltip, pos.top);
tooltip.css({
left: posLeft.px,
top: posTop.px
}).removeClass("left-top left-bottom right-top right-bottom").addClass(posLeft.backgroundPositionAlignment + "-" + posTop.backgroundPositionAlignment).fadeIn("fast");
target.mouseleave(function(event) {
event.stopPropagation();
$("#tooltip").stop(false, true).fadeOut("fast", function() {
$(this).css({
top: 0,
left: 0
});
});
});
}
},
/** Class: Candy.View.Pane.Context
* Context menu for actions and settings
*/
Context: {
/** Function: init
* Initialize context menu and setup mouseleave handler.
*/
init: function() {
if ($("#context-menu").length === 0) {
var html = Mustache.to_html(Candy.View.Template.Chat.Context.menu);
$("#chat-pane").append(html);
$("#context-menu").mouseleave(function() {
$(this).fadeOut("fast");
});
}
},
/** Function: show
* Show context menu (positions it according to the window height/width)
*
* Parameters:
* (Element) elem - On which element it should be shown
* (String) roomJid - Room Jid of the room it should be shown
* (Candy.Core.chatUser) user - User
*
* Uses:
* <getMenuLinks> for getting menulinks the user has access to
* <Candy.Util.getPosLeftAccordingToWindowBounds> for positioning
* <Candy.Util.getPosTopAccordingToWindowBounds> for positioning
*
* Triggers:
* candy:view.roster.after-context-menu using {roomJid, user, elements}
*/
show: function(elem, roomJid, user) {
elem = $(elem);
var roomId = self.Chat.rooms[roomJid].id, menu = $("#context-menu"), links = $("ul li", menu);
$("#tooltip").hide();
// add specific context-user class if a user is available (when context menu should be opened next to a user)
if (!user) {
user = Candy.Core.getUser();
}
links.remove();
var menulinks = this.getMenuLinks(roomJid, user, elem), id, clickHandler = function(roomJid, user) {
return function(event) {
event.data.callback(event, roomJid, user);
$("#context-menu").hide();
};
};
for (id in menulinks) {
if (menulinks.hasOwnProperty(id)) {
var link = menulinks[id], html = Mustache.to_html(Candy.View.Template.Chat.Context.menulinks, {
roomId: roomId,
"class": link["class"],
id: id,
label: link.label
});
$("ul", menu).append(html);
$("#context-menu-" + id).bind("click", link, clickHandler(roomJid, user));
}
}
// if `id` is set the menu is not empty
if (id) {
var pos = elem.offset(), posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(menu, pos.left), posTop = Candy.Util.getPosTopAccordingToWindowBounds(menu, pos.top);
menu.css({
left: posLeft.px,
top: posTop.px
}).removeClass("left-top left-bottom right-top right-bottom").addClass(posLeft.backgroundPositionAlignment + "-" + posTop.backgroundPositionAlignment).fadeIn("fast");
/** Event: candy:view.roster.after-context-menu
* After context menu display
*
* Parameters:
* (String) roomJid - room where the context menu has been triggered
* (Candy.Core.ChatUser) user - User
* (jQuery.Element) element - Menu element
*/
$(Candy).triggerHandler("candy:view.roster.after-context-menu", {
roomJid: roomJid,
user: user,
element: menu
});
return true;
}
},
/** Function: getMenuLinks
* Extends <initialMenuLinks> with menu links gathered from candy:view.roster.contextmenu
*
* Parameters:
* (String) roomJid - Room in which the menu will be displayed
* (Candy.Core.ChatUser) user - User
* (jQuery.Element) elem - Parent element of the context menu
*
* Triggers:
* candy:view.roster.context-menu using {roomJid, user, elem}
*
* Returns:
* (Object) - object containing the extended menulinks.
*/
getMenuLinks: function(roomJid, user, elem) {
var menulinks, id;
var evtData = {
roomJid: roomJid,
user: user,
elem: elem,
menulinks: this.initialMenuLinks(elem)
};
/** Event: candy:view.roster.context-menu
* Modify existing menu links (add links)
*
* In order to modify the links you need to change the object passed with an additional
* key "menulinks" containing the menulink object.
*
* Parameters:
* (String) roomJid - Room on which the menu should be displayed
* (Candy.Core.ChatUser) user - User
* (jQuery.Element) elem - Parent element of the context menu
*/
$(Candy).triggerHandler("candy:view.roster.context-menu", evtData);
menulinks = evtData.menulinks;
for (id in menulinks) {
if (menulinks.hasOwnProperty(id) && menulinks[id].requiredPermission !== undefined && !menulinks[id].requiredPermission(user, self.Room.getUser(roomJid), elem)) {
delete menulinks[id];
}
}
return menulinks;
},
/** Function: initialMenuLinks
* Returns initial menulinks. The following are initial:
*
* - Private Chat
* - Ignore
* - Unignore
* - Kick
* - Ban
* - Change Subject
*
* Returns:
* (Object) - object containing those menulinks
*/
initialMenuLinks: function() {
return {
"private": {
requiredPermission: function(user, me) {
return me.getNick() !== user.getNick() && Candy.Core.getRoom(Candy.View.getCurrent().roomJid) && !Candy.Core.getUser().isInPrivacyList("ignore", user.getJid());
},
"class": "private",
label: $.i18n._("privateActionLabel"),
callback: function(e, roomJid, user) {
$("#user-" + Candy.Util.jidToId(roomJid) + "-" + Candy.Util.jidToId(user.getJid())).click();
}
},
ignore: {
requiredPermission: function(user, me) {
return me.getNick() !== user.getNick() && !Candy.Core.getUser().isInPrivacyList("ignore", user.getJid());
},
"class": "ignore",
label: $.i18n._("ignoreActionLabel"),
callback: function(e, roomJid, user) {
Candy.View.Pane.Room.ignoreUser(roomJid, user.getJid());
}
},
unignore: {
requiredPermission: function(user, me) {
return me.getNick() !== user.getNick() && Candy.Core.getUser().isInPrivacyList("ignore", user.getJid());
},
"class": "unignore",
label: $.i18n._("unignoreActionLabel"),
callback: function(e, roomJid, user) {
Candy.View.Pane.Room.unignoreUser(roomJid, user.getJid());
}
},
kick: {
requiredPermission: function(user, me) {
return me.getNick() !== user.getNick() && me.isModerator() && !user.isModerator();
},
"class": "kick",
label: $.i18n._("kickActionLabel"),
callback: function(e, roomJid, user) {
self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.contextModalForm, {
_label: $.i18n._("reason"),
_submit: $.i18n._("kickActionLabel")
}), true);
$("#context-modal-field").focus();
$("#context-modal-form").submit(function() {
Candy.Core.Action.Jabber.Room.Admin.UserAction(roomJid, user.getJid(), "kick", $("#context-modal-field").val());
self.Chat.Modal.hide();
return false;
});
}
},
ban: {
requiredPermission: function(user, me) {
return me.getNick() !== user.getNick() && me.isModerator() && !user.isModerator();
},
"class": "ban",
label: $.i18n._("banActionLabel"),
callback: function(e, roomJid, user) {
self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.contextModalForm, {
_label: $.i18n._("reason"),
_submit: $.i18n._("banActionLabel")
}), true);
$("#context-modal-field").focus();
$("#context-modal-form").submit(function() {
Candy.Core.Action.Jabber.Room.Admin.UserAction(roomJid, user.getJid(), "ban", $("#context-modal-field").val());
self.Chat.Modal.hide();
return false;
});
}
},
subject: {
requiredPermission: function(user, me) {
return me.getNick() === user.getNick() && me.isModerator();
},
"class": "subject",
label: $.i18n._("setSubjectActionLabel"),
callback: function(e, roomJid) {
self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.contextModalForm, {
_label: $.i18n._("subject"),
_submit: $.i18n._("setSubjectActionLabel")
}), true);
$("#context-modal-field").focus();
$("#context-modal-form").submit(function(e) {
Candy.Core.Action.Jabber.Room.Admin.SetSubject(roomJid, $("#context-modal-field").val());
self.Chat.Modal.hide();
e.preventDefault();
});
}
}
};
},
/** Function: showEmoticonsMenu
* Shows the special emoticons menu
*
* Parameters:
* (Element) elem - Element on which it should be positioned to.
*
* Returns:
* (Boolean) - true
*/
showEmoticonsMenu: function(elem) {
elem = $(elem);
var pos = elem.offset(), menu = $("#context-menu"), content = $("ul", menu), emoticons = "", i;
$("#tooltip").hide();
for (i = Candy.Util.Parser.emoticons.length - 1; i >= 0; i--) {
emoticons = '<img src="' + Candy.Util.Parser._emoticonPath + Candy.Util.Parser.emoticons[i].image + '" alt="' + Candy.Util.Parser.emoticons[i].plain + '" />' + emoticons;
}
content.html('<li class="emoticons">' + emoticons + "</li>");
content.find("img").click(function() {
var input = Candy.View.Pane.Room.getPane(Candy.View.getCurrent().roomJid, ".message-form").children(".field"), value = input.val(), emoticon = $(this).attr("alt") + " ";
input.val(value ? value + " " + emoticon : emoticon).focus();
// Once you make a selction, hide the menu.
menu.hide();
});
var posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(menu, pos.left), posTop = Candy.Util.getPosTopAccordingToWindowBounds(menu, pos.top);
menu.css({
left: posLeft.px,
top: posTop.px
}).removeClass("left-top left-bottom right-top right-bottom").addClass(posLeft.backgroundPositionAlignment + "-" + posTop.backgroundPositionAlignment).fadeIn("fast");
return true;
}
}
};
return self;
}(Candy.View.Pane || {}, jQuery);
/** File: message.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Mustache, jQuery */
/** Class: Candy.View.Pane
* Candy view pane handles everything regarding DOM updates etc.
*
* Parameters:
* (Candy.View.Pane) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Pane = function(self, $) {
/** Class: Candy.View.Pane.Message
* Message submit/show handling
*/
self.Message = {
/** Function: submit
* on submit handler for message field sends the message to the server and if it's a private chat, shows the message
* immediately because the server doesn't send back those message.
*
* Parameters:
* (Event) event - Triggered event
*
* Triggers:
* candy:view.message.before-send using {message}
*
* FIXME: as everywhere, `roomJid` might be slightly incorrect in this case
* - maybe rename this as part of a refactoring.
*/
submit: function(event) {
var roomJid = Candy.View.getCurrent().roomJid, room = Candy.View.Pane.Chat.rooms[roomJid], roomType = room.type, targetJid = room.targetJid, message = $(this).children(".field").val().substring(0, Candy.View.getOptions().crop.message.body), xhtmlMessage, evtData = {
roomJid: roomJid,
message: message,
xhtmlMessage: xhtmlMessage
};
/** Event: candy:view.message.before-send
* Before sending a message
*
* Parameters:
* (String) roomJid - room to which the message should be sent
* (String) message - Message text
* (String) xhtmlMessage - XHTML formatted message [default: undefined]
*
* Returns:
* Boolean|undefined - if you like to stop sending the message, return false.
*/
if ($(Candy).triggerHandler("candy:view.message.before-send", evtData) === false) {
event.preventDefault();
return;
}
message = evtData.message;
xhtmlMessage = evtData.xhtmlMessage;
Candy.Core.Action.Jabber.Room.Message(targetJid, message, roomType, xhtmlMessage);
// Private user chat. Jabber won't notify the user who has sent the message. Just show it as the user hits the button...
if (roomType === "chat" && message) {
self.Message.show(roomJid, self.Room.getUser(roomJid).getNick(), message, xhtmlMessage, undefined, Candy.Core.getUser().getJid());
}
// Clear input and set focus to it
$(this).children(".field").val("").focus();
event.preventDefault();
},
/** Function: show
* Show a message in the message pane
*
* Parameters:
* (String) roomJid - room in which the message has been sent to
* (String) name - Name of the user which sent the message
* (String) message - Message
* (String) xhtmlMessage - XHTML formatted message [if options enableXHTML is true]
* (String) timestamp - [optional] Timestamp of the message, if not present, current date.
* (Boolean) carbon - [optional] Indication of wether or not the message was a carbon
*
* Triggers:
* candy:view.message.before-show using {roomJid, name, message}
* candy.view.message.before-render using {template, templateData}
* candy:view.message.after-show using {roomJid, name, message, element}
*/
show: function(roomJid, name, message, xhtmlMessage, timestamp, from, carbon, stanza) {
message = Candy.Util.Parser.all(message.substring(0, Candy.View.getOptions().crop.message.body));
if (Candy.View.getOptions().enableXHTML === true && xhtmlMessage) {
xhtmlMessage = Candy.Util.parseAndCropXhtml(xhtmlMessage, Candy.View.getOptions().crop.message.body);
}
timestamp = timestamp || new Date();
// Assume we have an ISO-8601 date string and convert it to a Date object
if (!timestamp.toDateString) {
timestamp = Candy.Util.iso8601toDate(timestamp);
}
// Before we add the new message, check to see if we should be automatically scrolling or not.
var messagePane = self.Room.getPane(roomJid, ".message-pane");
var enableScroll = messagePane.scrollTop() + messagePane.outerHeight() === messagePane.prop("scrollHeight") || !$(messagePane).is(":visible");
Candy.View.Pane.Chat.rooms[roomJid].enableScroll = enableScroll;
var evtData = {
roomJid: roomJid,
name: name,
message: message,
xhtmlMessage: xhtmlMessage,
from: from,
stanza: stanza
};
/** Event: candy:view.message.before-show
* Before showing a new message
*
* Parameters:
* (String) roomJid - Room JID
* (String) name - Name of the sending user
* (String) message - Message text
*
* Returns:
* Boolean - if you don't want to show the message, return false
*/
if ($(Candy).triggerHandler("candy:view.message.before-show", evtData) === false) {
return;
}
message = evtData.message;
xhtmlMessage = evtData.xhtmlMessage;
if (xhtmlMessage !== undefined && xhtmlMessage.length > 0) {
message = xhtmlMessage;
}
if (!message) {
return;
}
var renderEvtData = {
template: Candy.View.Template.Message.item,
templateData: {
name: name,
displayName: Candy.Util.crop(name, Candy.View.getOptions().crop.message.nickname),
message: message,
time: Candy.Util.localizedTime(timestamp),
timestamp: timestamp.toISOString(),
roomjid: roomJid,
from: from
},
stanza: stanza
};
/** Event: candy:view.message.before-render
* Before rendering the message element
*
* Parameters:
* (String) template - Template to use
* (Object) templateData - Template data consists of:
* - (String) name - Name of the sending user
* - (String) displayName - Cropped name of the sending user
* - (String) message - Message text
* - (String) time - Localized time of message
* - (String) timestamp - ISO formatted timestamp of message
*/
$(Candy).triggerHandler("candy:view.message.before-render", renderEvtData);
var html = Mustache.to_html(renderEvtData.template, renderEvtData.templateData);
self.Room.appendToMessagePane(roomJid, html);
var elem = self.Room.getPane(roomJid, ".message-pane").children().last();
// click on username opens private chat
elem.find("a.label").click(function(event) {
event.preventDefault();
// Check if user is online and not myself
var room = Candy.Core.getRoom(roomJid);
if (room && name !== self.Room.getUser(Candy.View.getCurrent().roomJid).getNick() && room.getRoster().get(roomJid + "/" + name)) {
if (Candy.View.Pane.PrivateRoom.open(roomJid + "/" + name, name, true) === false) {
return false;
}
}
});
if (!carbon) {
var notifyEvtData = {
name: name,
displayName: Candy.Util.crop(name, Candy.View.getOptions().crop.message.nickname),
roomJid: roomJid,
message: message,
time: Candy.Util.localizedTime(timestamp),
timestamp: timestamp.toISOString()
};
/** Event: candy:view.message.notify
* Notify the user (optionally) that a new message has been received
*
* Parameters:
* (Object) templateData - Template data consists of:
* - (String) name - Name of the sending user
* - (String) displayName - Cropped name of the sending user
* - (String) roomJid - JID into which the message was sent
* - (String) message - Message text
* - (String) time - Localized time of message
* - (String) timestamp - ISO formatted timestamp of message
* - (Boolean) carbon - Indication of wether or not the message was a carbon
*/
$(Candy).triggerHandler("candy:view.message.notify", notifyEvtData);
// Check to see if in-core notifications are disabled
if (!Candy.Core.getOptions().disableCoreNotifications) {
if (Candy.View.getCurrent().roomJid !== roomJid || !self.Window.hasFocus()) {
self.Chat.increaseUnreadMessages(roomJid);
if (!self.Window.hasFocus()) {
// Notify the user about a new private message OR on all messages if configured
if (Candy.View.Pane.Chat.rooms[roomJid].type === "chat" || Candy.View.getOptions().updateWindowOnAllMessages === true) {
self.Chat.Toolbar.playSound();
}
}
}
}
if (Candy.View.getCurrent().roomJid === roomJid) {
self.Room.scrollToBottom(roomJid);
}
}
evtData.element = elem;
/** Event: candy:view.message.after-show
* Triggered after showing a message
*
* Parameters:
* (String) roomJid - Room JID
* (jQuery.Element) element - User element
* (String) name - Name of the sending user
* (String) message - Message text
*/
$(Candy).triggerHandler("candy:view.message.after-show", evtData);
}
};
return self;
}(Candy.View.Pane || {}, jQuery);
/** File: privateRoom.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Strophe, jQuery */
/** Class: Candy.View.Pane
* Candy view pane handles everything regarding DOM updates etc.
*
* Parameters:
* (Candy.View.Pane) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Pane = function(self, $) {
/** Class: Candy.View.Pane.PrivateRoom
* Private room handling
*/
self.PrivateRoom = {
/** Function: open
* Opens a new private room
*
* Parameters:
* (String) roomJid - Room jid to open
* (String) roomName - Room name
* (Boolean) switchToRoom - If true, displayed room switches automatically to this room
* (e.g. when user clicks itself on another user to open a private chat)
* (Boolean) isNoConferenceRoomJid - true if a 3rd-party client sends a direct message to this user (not via the room)
* then the username is the node and not the resource. This param addresses this case.
*
* Triggers:
* candy:view.private-room.after-open using {roomJid, type, element}
*/
open: function(roomJid, roomName, switchToRoom, isNoConferenceRoomJid) {
var user = isNoConferenceRoomJid ? Candy.Core.getUser() : self.Room.getUser(Strophe.getBareJidFromJid(roomJid)), evtData = {
roomJid: roomJid,
roomName: roomName,
type: "chat"
};
/** Event: candy:view.private-room.before-open
* Before opening a new private room
*
* Parameters:
* (String) roomJid - Room JID
* (String) roomName - Room name
* (String) type - 'chat'
*
* Returns:
* Boolean - if you don't want to open the private room, return false
*/
if ($(Candy).triggerHandler("candy:view.private-room.before-open", evtData) === false) {
return false;
}
// if target user is in privacy list, don't open the private chat.
if (Candy.Core.getUser().isInPrivacyList("ignore", roomJid)) {
return false;
}
if (!self.Chat.rooms[roomJid]) {
if (self.Room.init(roomJid, roomName, "chat") === false) {
return false;
}
}
if (switchToRoom) {
self.Room.show(roomJid);
}
self.Roster.update(roomJid, new Candy.Core.ChatUser(roomJid, roomName), "join", user);
self.Roster.update(roomJid, user, "join", user);
self.PrivateRoom.setStatus(roomJid, "join");
evtData.element = self.Room.getPane(roomJid);
/** Event: candy:view.private-room.after-open
* After opening a new private room
*
* Parameters:
* (String) roomJid - Room JID
* (String) type - 'chat'
* (jQuery.Element) element - User element
*/
$(Candy).triggerHandler("candy:view.private-room.after-open", evtData);
},
/** Function: setStatus
* Set offline or online status for private rooms (when one of the participants leaves the room)
*
* Parameters:
* (String) roomJid - Private room jid
* (String) status - "leave"/"join"
*/
setStatus: function(roomJid, status) {
var messageForm = self.Room.getPane(roomJid, ".message-form");
if (status === "join") {
self.Chat.getTab(roomJid).addClass("online").removeClass("offline");
messageForm.children(".field").removeAttr("disabled");
messageForm.children(".submit").removeAttr("disabled");
self.Chat.getTab(roomJid);
} else if (status === "leave") {
self.Chat.getTab(roomJid).addClass("offline").removeClass("online");
messageForm.children(".field").attr("disabled", true);
messageForm.children(".submit").attr("disabled", true);
}
},
/** Function: changeNick
* Changes the nick for every private room opened with this roomJid.
*
* Parameters:
* (String) roomJid - Public room jid
* (Candy.Core.ChatUser) user - User which changes his nick
*/
changeNick: function(roomJid, user) {
Candy.Core.log("[View:Pane:PrivateRoom] changeNick");
var previousPrivateRoomJid = roomJid + "/" + user.getPreviousNick(), newPrivateRoomJid = roomJid + "/" + user.getNick(), previousPrivateRoomId = Candy.Util.jidToId(previousPrivateRoomJid), newPrivateRoomId = Candy.Util.jidToId(newPrivateRoomJid), room = self.Chat.rooms[previousPrivateRoomJid], roomElement, roomTabElement;
// it could happen that the new private room is already existing -> close it first.
// if this is not done, errors appear as two rooms would have the same id
if (self.Chat.rooms[newPrivateRoomJid]) {
self.Room.close(newPrivateRoomJid);
}
if (room) {
/* someone I talk with, changed nick */
room.name = user.getNick();
room.id = newPrivateRoomId;
self.Chat.rooms[newPrivateRoomJid] = room;
delete self.Chat.rooms[previousPrivateRoomJid];
roomElement = $("#chat-room-" + previousPrivateRoomId);
if (roomElement) {
roomElement.attr("data-roomjid", newPrivateRoomJid);
roomElement.attr("id", "chat-room-" + newPrivateRoomId);
roomTabElement = $('#chat-tabs li[data-roomjid="' + previousPrivateRoomJid + '"]');
roomTabElement.attr("data-roomjid", newPrivateRoomJid);
/* TODO: The '@' is defined in the template. Somehow we should
* extract both things into our CSS or do something else to prevent that.
*/
roomTabElement.children("a.label").text("@" + user.getNick());
if (Candy.View.getCurrent().roomJid === previousPrivateRoomJid) {
Candy.View.getCurrent().roomJid = newPrivateRoomJid;
}
}
} else {
/* I changed the nick */
roomElement = $('.room-pane.roomtype-chat[data-userjid="' + previousPrivateRoomJid + '"]');
if (roomElement.length) {
previousPrivateRoomId = Candy.Util.jidToId(roomElement.attr("data-roomjid"));
roomElement.attr("data-userjid", newPrivateRoomJid);
}
}
if (roomElement && roomElement.length) {
self.Roster.changeNick(previousPrivateRoomId, user);
}
}
};
return self;
}(Candy.View.Pane || {}, jQuery);
/** File: room.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Mustache, Strophe, jQuery */
/** Class: Candy.View.Pane
* Candy view pane handles everything regarding DOM updates etc.
*
* Parameters:
* (Candy.View.Pane) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Pane = function(self, $) {
/** Class: Candy.View.Pane.Room
* Everything which belongs to room view things belongs here.
*/
self.Room = {
/** Function: init
* Initialize a new room and inserts the room html into the DOM
*
* Parameters:
* (String) roomJid - Room JID
* (String) roomName - Room name
* (String) roomType - Type: either "groupchat" or "chat" (private chat)
*
* Uses:
* - <Candy.Util.jidToId>
* - <Candy.View.Pane.Chat.addTab>
* - <getPane>
*
* Triggers:
* candy:view.room.after-add using {roomJid, type, element}
*
* Returns:
* (String) - the room id of the element created.
*/
init: function(roomJid, roomName, roomType) {
roomType = roomType || "groupchat";
roomJid = Candy.Util.unescapeJid(roomJid);
var evtData = {
roomJid: roomJid,
type: roomType
};
/** Event: candy:view.room.before-add
* Before initialising a room
*
* Parameters:
* (String) roomJid - Room JID
* (String) type - Room Type
*
* Returns:
* Boolean - if you don't want to initialise the room, return false.
*/
if ($(Candy).triggerHandler("candy:view.room.before-add", evtData) === false) {
return false;
}
// First room, show sound control
if (Candy.Util.isEmptyObject(self.Chat.rooms)) {
self.Chat.Toolbar.show();
self.Chat.showMobileIcon();
}
var roomId = Candy.Util.jidToId(roomJid);
self.Chat.rooms[roomJid] = {
id: roomId,
usercount: 0,
name: roomName,
type: roomType,
messageCount: 0,
scrollPosition: -1,
targetJid: roomJid
};
$("#chat-rooms").append(Mustache.to_html(Candy.View.Template.Room.pane, {
roomId: roomId,
roomJid: roomJid,
roomType: roomType,
form: {
_messageSubmit: $.i18n._("messageSubmit")
},
roster: {
_userOnline: $.i18n._("userOnline")
}
}, {
roster: Candy.View.Template.Roster.pane,
messages: Candy.View.Template.Message.pane,
form: Candy.View.Template.Room.form
}));
self.Chat.addTab(roomJid, roomName, roomType);
self.Room.getPane(roomJid, ".message-form").submit(self.Message.submit);
self.Room.scrollToBottom(roomJid);
evtData.element = self.Room.getPane(roomJid);
/** Event: candy:view.room.after-add
* After initialising a room
*
* Parameters:
* (String) roomJid - Room JID
* (String) type - Room Type
* (jQuery.Element) element - Room element
*/
$(Candy).triggerHandler("candy:view.room.after-add", evtData);
return roomId;
},
/** Function: show
* Show a specific room and hides the other rooms (if there are any)
*
* Parameters:
* (String) roomJid - room jid to show
*
* Triggers:
* candy:view.room.after-show using {roomJid, element}
* candy:view.room.after-hide using {roomJid, element}
*/
show: function(roomJid) {
var roomId = self.Chat.rooms[roomJid].id, evtData;
$(".room-pane").each(function() {
var elem = $(this);
evtData = {
roomJid: elem.attr("data-roomjid"),
type: elem.attr("data-roomtype"),
element: elem
};
if (elem.attr("id") === "chat-room-" + roomId) {
elem.show();
Candy.View.getCurrent().roomJid = roomJid;
self.Chat.setActiveTab(roomJid);
self.Chat.Toolbar.update(roomJid);
self.Chat.clearUnreadMessages(roomJid);
self.Room.setFocusToForm(roomJid);
self.Room.scrollToBottom(roomJid);
/** Event: candy:view.room.after-show
* After showing a room
*
* Parameters:
* (String) roomJid - Room JID
* (String) type - Room Type
* (jQuery.Element) element - Room element
*/
$(Candy).triggerHandler("candy:view.room.after-show", evtData);
} else {
elem.hide();
/** Event: candy:view.room.after-hide
* After hiding a room
*
* Parameters:
* (String) roomJid - Room JID
* (String) type - Room Type
* (jQuery.Element) element - Room element
*/
$(Candy).triggerHandler("candy:view.room.after-hide", evtData);
}
});
},
/** Function: setSubject
* Called when someone changes the subject in the channel
*
* Triggers:
* candy:view.room.after-subject-change using {roomJid, element, subject}
*
* Parameters:
* (String) roomJid - Room Jid
* (String) subject - The new subject
*/
setSubject: function(roomJid, subject) {
subject = Candy.Util.Parser.linkify(Candy.Util.Parser.escape(subject));
var timestamp = new Date();
var html = Mustache.to_html(Candy.View.Template.Room.subject, {
subject: subject,
roomName: self.Chat.rooms[roomJid].name,
_roomSubject: $.i18n._("roomSubject"),
time: Candy.Util.localizedTime(timestamp),
timestamp: timestamp.toISOString()
});
self.Room.appendToMessagePane(roomJid, html);
self.Room.scrollToBottom(roomJid);
/** Event: candy:view.room.after-subject-change
* After changing the subject of a room
*
* Parameters:
* (String) roomJid - Room JID
* (jQuery.Element) element - Room element
* (String) subject - New subject
*/
$(Candy).triggerHandler("candy:view.room.after-subject-change", {
roomJid: roomJid,
element: self.Room.getPane(roomJid),
subject: subject
});
},
/** Function: close
* Close a room and remove everything in the DOM belonging to this room.
*
* NOTICE: There's a rendering bug in Opera when all rooms have been closed.
* (Take a look in the source for a more detailed description)
*
* Triggers:
* candy:view.room.after-close using {roomJid}
*
* Parameters:
* (String) roomJid - Room to close
*/
close: function(roomJid) {
self.Chat.removeTab(roomJid);
self.Window.clearUnreadMessages();
/* TODO:
There's a rendering bug in Opera which doesn't redraw (remove) the message form.
Only a cosmetical issue (when all tabs are closed) but it's annoying...
This happens when form has no focus too. Maybe it's because of CSS positioning.
*/
self.Room.getPane(roomJid).remove();
var openRooms = $("#chat-rooms").children();
if (Candy.View.getCurrent().roomJid === roomJid) {
Candy.View.getCurrent().roomJid = null;
if (openRooms.length === 0) {
self.Chat.allTabsClosed();
} else {
self.Room.show(openRooms.last().attr("data-roomjid"));
}
}
delete self.Chat.rooms[roomJid];
/** Event: candy:view.room.after-close
* After closing a room
*
* Parameters:
* (String) roomJid - Room JID
*/
$(Candy).triggerHandler("candy:view.room.after-close", {
roomJid: roomJid
});
},
/** Function: appendToMessagePane
* Append a new message to the message pane.
*
* Parameters:
* (String) roomJid - Room JID
* (String) html - rendered message html
*/
appendToMessagePane: function(roomJid, html) {
self.Room.getPane(roomJid, ".message-pane").append(html);
self.Chat.rooms[roomJid].messageCount++;
self.Room.sliceMessagePane(roomJid);
},
/** Function: sliceMessagePane
* Slices the message pane after the max amount of messages specified in the Candy View options (limit setting).
*
* This is done to hopefully prevent browsers from getting slow after a certain amount of messages in the DOM.
*
* The slice is only done when autoscroll is on, because otherwise someone might lose exactly the message he want to look for.
*
* Parameters:
* (String) roomJid - Room JID
*/
sliceMessagePane: function(roomJid) {
// Only clean if autoscroll is enabled
if (self.Window.autoscroll) {
var options = Candy.View.getOptions().messages;
if (self.Chat.rooms[roomJid].messageCount > options.limit) {
self.Room.getPane(roomJid, ".message-pane").children().slice(0, options.remove).remove();
self.Chat.rooms[roomJid].messageCount -= options.remove;
}
}
},
/** Function: scrollToBottom
* Scroll to bottom wrapper for <onScrollToBottom> to be able to disable it by overwriting the function.
*
* Parameters:
* (String) roomJid - Room JID
*
* Uses:
* - <onScrollToBottom>
*/
scrollToBottom: function(roomJid) {
self.Room.onScrollToBottom(roomJid);
},
/** Function: onScrollToBottom
* Scrolls to the latest message received/sent.
*
* Parameters:
* (String) roomJid - Room JID
*/
onScrollToBottom: function(roomJid) {
var messagePane = self.Room.getPane(roomJid, ".message-pane-wrapper");
if (Candy.View.Pane.Chat.rooms[roomJid].enableScroll === true) {
messagePane.scrollTop(messagePane.prop("scrollHeight"));
} else {
return false;
}
},
/** Function: onScrollToStoredPosition
* When autoscroll is off, the position where the scrollbar is has to be stored for each room, because it otherwise
* goes to the top in the message window.
*
* Parameters:
* (String) roomJid - Room JID
*/
onScrollToStoredPosition: function(roomJid) {
// This should only apply when entering a room...
// ... therefore we set scrollPosition to -1 after execution.
if (self.Chat.rooms[roomJid].scrollPosition > -1) {
var messagePane = self.Room.getPane(roomJid, ".message-pane-wrapper");
messagePane.scrollTop(self.Chat.rooms[roomJid].scrollPosition);
self.Chat.rooms[roomJid].scrollPosition = -1;
}
},
/** Function: setFocusToForm
* Set focus to the message input field within the message form.
*
* Parameters:
* (String) roomJid - Room JID
*/
setFocusToForm: function(roomJid) {
// If we're on mobile, don't focus the input field.
if (Candy.Util.isMobile()) {
return true;
}
var pane = self.Room.getPane(roomJid, ".message-form");
if (pane) {
// IE8 will fail maybe, because the field isn't there yet.
try {
pane.children(".field")[0].focus();
} catch (e) {}
}
},
/** Function: setUser
* Sets or updates the current user in the specified room (called by <Candy.View.Pane.Roster.update>) and set specific informations
* (roles and affiliations) on the room tab (chat-pane).
*
* Parameters:
* (String) roomJid - Room in which the user is set to.
* (Candy.Core.ChatUser) user - The user
*/
setUser: function(roomJid, user) {
self.Chat.rooms[roomJid].user = user;
var roomPane = self.Room.getPane(roomJid), chatPane = $("#chat-pane");
roomPane.attr("data-userjid", user.getJid());
// Set classes based on user role / affiliation
if (user.isModerator()) {
if (user.getRole() === user.ROLE_MODERATOR) {
chatPane.addClass("role-moderator");
}
if (user.getAffiliation() === user.AFFILIATION_OWNER) {
chatPane.addClass("affiliation-owner");
}
} else {
chatPane.removeClass("role-moderator affiliation-owner");
}
self.Chat.Context.init();
},
/** Function: getUser
* Get the current user in the room specified with the jid
*
* Parameters:
* (String) roomJid - Room of which the user should be returned from
*
* Returns:
* (Candy.Core.ChatUser) - user
*/
getUser: function(roomJid) {
return self.Chat.rooms[roomJid].user;
},
/** Function: ignoreUser
* Ignore specified user and add the ignore icon to the roster item of the user
*
* Parameters:
* (String) roomJid - Room in which the user should be ignored
* (String) userJid - User which should be ignored
*/
ignoreUser: function(roomJid, userJid) {
Candy.Core.Action.Jabber.Room.IgnoreUnignore(userJid);
Candy.View.Pane.Room.addIgnoreIcon(roomJid, userJid);
},
/** Function: unignoreUser
* Unignore an ignored user and remove the ignore icon of the roster item.
*
* Parameters:
* (String) roomJid - Room in which the user should be unignored
* (String) userJid - User which should be unignored
*/
unignoreUser: function(roomJid, userJid) {
Candy.Core.Action.Jabber.Room.IgnoreUnignore(userJid);
Candy.View.Pane.Room.removeIgnoreIcon(roomJid, userJid);
},
/** Function: addIgnoreIcon
* Add the ignore icon to the roster item of the specified user
*
* Parameters:
* (String) roomJid - Room in which the roster item should be updated
* (String) userJid - User of which the roster item should be updated
*/
addIgnoreIcon: function(roomJid, userJid) {
if (Candy.View.Pane.Chat.rooms[userJid]) {
$("#user-" + Candy.View.Pane.Chat.rooms[userJid].id + "-" + Candy.Util.jidToId(userJid)).addClass("status-ignored");
}
if (Candy.View.Pane.Chat.rooms[Strophe.getBareJidFromJid(roomJid)]) {
$("#user-" + Candy.View.Pane.Chat.rooms[Strophe.getBareJidFromJid(roomJid)].id + "-" + Candy.Util.jidToId(userJid)).addClass("status-ignored");
}
},
/** Function: removeIgnoreIcon
* Remove the ignore icon to the roster item of the specified user
*
* Parameters:
* (String) roomJid - Room in which the roster item should be updated
* (String) userJid - User of which the roster item should be updated
*/
removeIgnoreIcon: function(roomJid, userJid) {
if (Candy.View.Pane.Chat.rooms[userJid]) {
$("#user-" + Candy.View.Pane.Chat.rooms[userJid].id + "-" + Candy.Util.jidToId(userJid)).removeClass("status-ignored");
}
if (Candy.View.Pane.Chat.rooms[Strophe.getBareJidFromJid(roomJid)]) {
$("#user-" + Candy.View.Pane.Chat.rooms[Strophe.getBareJidFromJid(roomJid)].id + "-" + Candy.Util.jidToId(userJid)).removeClass("status-ignored");
}
},
/** Function: getPane
* Get the chat room pane or a subPane of it (if subPane is specified)
*
* Parameters:
* (String) roomJid - Room in which the pane lies
* (String) subPane - Sub pane of the chat room pane if needed [optional]
*/
getPane: function(roomJid, subPane) {
if (self.Chat.rooms[roomJid]) {
if (subPane) {
if (self.Chat.rooms[roomJid]["pane-" + subPane]) {
return self.Chat.rooms[roomJid]["pane-" + subPane];
} else {
self.Chat.rooms[roomJid]["pane-" + subPane] = $("#chat-room-" + self.Chat.rooms[roomJid].id).find(subPane);
return self.Chat.rooms[roomJid]["pane-" + subPane];
}
} else {
return $("#chat-room-" + self.Chat.rooms[roomJid].id);
}
}
},
/** Function: changeDataUserJidIfUserIsMe
* Changes the room's data-userjid attribute if the specified user is the current user.
*
* Parameters:
* (String) roomId - Id of the room
* (Candy.Core.ChatUser) user - User
*/
changeDataUserJidIfUserIsMe: function(roomId, user) {
if (user.getNick() === Candy.Core.getUser().getNick()) {
var roomElement = $("#chat-room-" + roomId);
roomElement.attr("data-userjid", Strophe.getBareJidFromJid(roomElement.attr("data-userjid")) + "/" + user.getNick());
}
}
};
return self;
}(Candy.View.Pane || {}, jQuery);
/** File: roster.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, Mustache, Strophe, jQuery */
/** Class: Candy.View.Pane
* Candy view pane handles everything regarding DOM updates etc.
*
* Parameters:
* (Candy.View.Pane) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Pane = function(self, $) {
/** Class Candy.View.Pane.Roster
* Handles everyhing regarding roster updates.
*/
self.Roster = {
/** Function: update
* Called by <Candy.View.Observer.Presence.update> to update the roster if needed.
* Adds/removes users from the roster list or updates informations on their items (roles, affiliations etc.)
*
* TODO: Refactoring, this method has too much LOC.
*
* Parameters:
* (String) roomJid - Room JID in which the update happens
* (Candy.Core.ChatUser) user - User on which the update happens
* (String) action - one of "join", "leave", "kick" and "ban"
* (Candy.Core.ChatUser) currentUser - Current user
*
* Triggers:
* candy:view.roster.before-update using {roomJid, user, action, element}
* candy:view.roster.after-update using {roomJid, user, action, element}
*/
update: function(roomJid, user, action, currentUser) {
Candy.Core.log("[View:Pane:Roster] " + action);
var roomId = self.Chat.rooms[roomJid].id, userId = Candy.Util.jidToId(user.getJid()), usercountDiff = -1, userElem = $("#user-" + roomId + "-" + userId), evtData = {
roomJid: roomJid,
user: user,
action: action,
element: userElem
};
/** Event: candy:view.roster.before-update
* Before updating the roster of a room
*
* Parameters:
* (String) roomJid - Room JID
* (Candy.Core.ChatUser) user - User
* (String) action - [join, leave, kick, ban]
* (jQuery.Element) element - User element
*/
$(Candy).triggerHandler("candy:view.roster.before-update", evtData);
// a user joined the room
if (action === "join") {
usercountDiff = 1;
if (userElem.length < 1) {
self.Roster._insertUser(roomJid, roomId, user, userId, currentUser);
self.Roster.showJoinAnimation(user, userId, roomId, roomJid, currentUser);
} else {
usercountDiff = 0;
userElem.remove();
self.Roster._insertUser(roomJid, roomId, user, userId, currentUser);
// it's me, update the toolbar
if (currentUser !== undefined && user.getNick() === currentUser.getNick() && self.Room.getUser(roomJid)) {
self.Chat.Toolbar.update(roomJid);
}
}
// Presence of client
if (currentUser !== undefined && currentUser.getNick() === user.getNick()) {
self.Room.setUser(roomJid, user);
} else {
$("#user-" + roomId + "-" + userId).click(self.Roster.userClick);
}
$("#user-" + roomId + "-" + userId + " .context").click(function(e) {
self.Chat.Context.show(e.currentTarget, roomJid, user);
e.stopPropagation();
});
// check if current user is ignoring the user who has joined.
if (currentUser !== undefined && currentUser.isInPrivacyList("ignore", user.getJid())) {
Candy.View.Pane.Room.addIgnoreIcon(roomJid, user.getJid());
}
} else if (action === "leave") {
self.Roster.leaveAnimation("user-" + roomId + "-" + userId);
// always show leave message in private room, even if status messages have been disabled
if (self.Chat.rooms[roomJid].type === "chat") {
self.Chat.onInfoMessage(roomJid, null, $.i18n._("userLeftRoom", [ user.getNick() ]));
} else {
self.Chat.infoMessage(roomJid, null, $.i18n._("userLeftRoom", [ user.getNick() ]), "");
}
} else if (action === "nickchange") {
usercountDiff = 0;
self.Roster.changeNick(roomId, user);
self.Room.changeDataUserJidIfUserIsMe(roomId, user);
self.PrivateRoom.changeNick(roomJid, user);
var infoMessage = $.i18n._("userChangedNick", [ user.getPreviousNick(), user.getNick() ]);
self.Chat.infoMessage(roomJid, null, infoMessage);
} else if (action === "kick") {
self.Roster.leaveAnimation("user-" + roomId + "-" + userId);
self.Chat.onInfoMessage(roomJid, null, $.i18n._("userHasBeenKickedFromRoom", [ user.getNick() ]));
} else if (action === "ban") {
self.Roster.leaveAnimation("user-" + roomId + "-" + userId);
self.Chat.onInfoMessage(roomJid, null, $.i18n._("userHasBeenBannedFromRoom", [ user.getNick() ]));
}
// Update user count
Candy.View.Pane.Chat.rooms[roomJid].usercount += usercountDiff;
if (roomJid === Candy.View.getCurrent().roomJid) {
Candy.View.Pane.Chat.Toolbar.updateUsercount(Candy.View.Pane.Chat.rooms[roomJid].usercount);
}
// in case there's been a join, the element is now there (previously not)
evtData.element = $("#user-" + roomId + "-" + userId);
/** Event: candy:view.roster.after-update
* After updating a room's roster
*
* Parameters:
* (String) roomJid - Room JID
* (Candy.Core.ChatUser) user - User
* (String) action - [join, leave, kick, ban]
* (jQuery.Element) element - User element
*/
$(Candy).triggerHandler("candy:view.roster.after-update", evtData);
},
_insertUser: function(roomJid, roomId, user, userId, currentUser) {
var contact = user.getContact();
var html = Mustache.to_html(Candy.View.Template.Roster.user, {
roomId: roomId,
userId: userId,
userJid: user.getJid(),
realJid: user.getRealJid(),
status: user.getStatus(),
contact_status: contact ? contact.getStatus() : "unavailable",
nick: user.getNick(),
displayNick: Candy.Util.crop(user.getNick(), Candy.View.getOptions().crop.roster.nickname),
role: user.getRole(),
affiliation: user.getAffiliation(),
me: currentUser !== undefined && user.getNick() === currentUser.getNick(),
tooltipRole: $.i18n._("tooltipRole"),
tooltipIgnored: $.i18n._("tooltipIgnored")
});
var userInserted = false, rosterPane = self.Room.getPane(roomJid, ".roster-pane");
// there are already users in the roster
if (rosterPane.children().length > 0) {
// insert alphabetically, sorted by status
var userSortCompare = self.Roster._userSortCompare(user.getNick(), user.getStatus());
rosterPane.children().each(function() {
var elem = $(this);
if (self.Roster._userSortCompare(elem.attr("data-nick"), elem.attr("data-status")) > userSortCompare) {
elem.before(html);
userInserted = true;
return false;
}
return true;
});
}
// first user in roster
if (!userInserted) {
rosterPane.append(html);
}
},
_userSortCompare: function(nick, status) {
var statusWeight;
switch (status) {
case "available":
statusWeight = 1;
break;
case "unavailable":
statusWeight = 9;
break;
default:
statusWeight = 8;
}
return statusWeight + nick.toUpperCase();
},
/** Function: userClick
* Click handler for opening a private room
*/
userClick: function() {
var elem = $(this), realJid = elem.attr("data-real-jid"), useRealJid = Candy.Core.getOptions().useParticipantRealJid && (realJid !== undefined && realJid !== null && realJid !== ""), targetJid = useRealJid && realJid ? Strophe.getBareJidFromJid(realJid) : elem.attr("data-jid");
self.PrivateRoom.open(targetJid, elem.attr("data-nick"), true, useRealJid);
},
/** Function: showJoinAnimation
* Shows join animation if needed
*
* FIXME: Refactor. Part of this will be done by the big room improvements
*/
showJoinAnimation: function(user, userId, roomId, roomJid, currentUser) {
// don't show if the user has recently changed the nickname.
var rosterUserId = "user-" + roomId + "-" + userId, $rosterUserElem = $("#" + rosterUserId);
if (!user.getPreviousNick() || !$rosterUserElem || $rosterUserElem.is(":visible") === false) {
self.Roster.joinAnimation(rosterUserId);
// only show other users joining & don't show if there's no message in the room.
if (currentUser !== undefined && user.getNick() !== currentUser.getNick() && self.Room.getUser(roomJid)) {
// always show join message in private room, even if status messages have been disabled
if (self.Chat.rooms[roomJid].type === "chat") {
self.Chat.onInfoMessage(roomJid, null, $.i18n._("userJoinedRoom", [ user.getNick() ]));
} else {
self.Chat.infoMessage(roomJid, null, $.i18n._("userJoinedRoom", [ user.getNick() ]));
}
}
}
},
/** Function: joinAnimation
* Animates specified elementId on join
*
* Parameters:
* (String) elementId - Specific element to do the animation on
*/
joinAnimation: function(elementId) {
$("#" + elementId).stop(true).slideDown("normal", function() {
$(this).animate({
opacity: 1
});
});
},
/** Function: leaveAnimation
* Leave animation for specified element id and removes the DOM element on completion.
*
* Parameters:
* (String) elementId - Specific element to do the animation on
*/
leaveAnimation: function(elementId) {
$("#" + elementId).stop(true).attr("id", "#" + elementId + "-leaving").animate({
opacity: 0
}, {
complete: function() {
$(this).slideUp("normal", function() {
$(this).remove();
});
}
});
},
/** Function: changeNick
* Change nick of an existing user in the roster
*
* UserId has to be recalculated from the user because at the time of this call,
* the user is already set with the new jid & nick.
*
* Parameters:
* (String) roomId - Id of the room
* (Candy.Core.ChatUser) user - User object
*/
changeNick: function(roomId, user) {
Candy.Core.log("[View:Pane:Roster] changeNick");
var previousUserJid = Strophe.getBareJidFromJid(user.getJid()) + "/" + user.getPreviousNick(), elementId = "user-" + roomId + "-" + Candy.Util.jidToId(previousUserJid), el = $("#" + elementId);
el.attr("data-nick", user.getNick());
el.attr("data-jid", user.getJid());
el.children("div.label").text(user.getNick());
el.attr("id", "user-" + roomId + "-" + Candy.Util.jidToId(user.getJid()));
}
};
return self;
}(Candy.View.Pane || {}, jQuery);
/** File: window.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy, jQuery, window */
/** Class: Candy.View.Pane
* Candy view pane handles everything regarding DOM updates etc.
*
* Parameters:
* (Candy.View.Pane) self - itself
* (jQuery) $ - jQuery
*/
Candy.View.Pane = function(self) {
/** Class: Candy.View.Pane.Window
* Window related view updates
*/
self.Window = {
/** PrivateVariable: _hasFocus
* Window has focus
*/
_hasFocus: true,
/** PrivateVariable: _plainTitle
* Document title
*/
_plainTitle: window.top.document.title,
/** PrivateVariable: _unreadMessagesCount
* Unread messages count
*/
_unreadMessagesCount: 0,
/** Variable: autoscroll
* Boolean whether autoscroll is enabled
*/
autoscroll: true,
/** Function: hasFocus
* Checks if window has focus
*
* Returns:
* (Boolean)
*/
hasFocus: function() {
return self.Window._hasFocus;
},
/** Function: increaseUnreadMessages
* Increases unread message count in window title by one.
*/
increaseUnreadMessages: function() {
self.Window.renderUnreadMessages(++self.Window._unreadMessagesCount);
},
/** Function: reduceUnreadMessages
* Reduce unread message count in window title by `num`.
*
* Parameters:
* (Integer) num - Unread message count will be reduced by this value
*/
reduceUnreadMessages: function(num) {
self.Window._unreadMessagesCount -= num;
if (self.Window._unreadMessagesCount <= 0) {
self.Window.clearUnreadMessages();
} else {
self.Window.renderUnreadMessages(self.Window._unreadMessagesCount);
}
},
/** Function: clearUnreadMessages
* Clear unread message count in window title.
*/
clearUnreadMessages: function() {
self.Window._unreadMessagesCount = 0;
window.top.document.title = self.Window._plainTitle;
},
/** Function: renderUnreadMessages
* Update window title to show message count.
*
* Parameters:
* (Integer) count - Number of unread messages to show in window title
*/
renderUnreadMessages: function(count) {
window.top.document.title = Candy.View.Template.Window.unreadmessages.replace("{{count}}", count).replace("{{title}}", self.Window._plainTitle);
},
/** Function: onFocus
* Window focus event handler.
*/
onFocus: function() {
self.Window._hasFocus = true;
if (Candy.View.getCurrent().roomJid) {
self.Room.setFocusToForm(Candy.View.getCurrent().roomJid);
self.Chat.clearUnreadMessages(Candy.View.getCurrent().roomJid);
}
},
/** Function: onBlur
* Window blur event handler.
*/
onBlur: function() {
self.Window._hasFocus = false;
}
};
return self;
}(Candy.View.Pane || {}, jQuery);
/** File: template.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy */
/** Class: Candy.View.Template
* Contains mustache.js templates
*/
Candy.View.Template = function(self) {
self.Window = {
/**
* Unread messages - used to extend the window title
*/
unreadmessages: "({{count}}) {{title}}"
};
// BAO added title on tabs
self.Chat = {
pane: '<div id="chat-pane">{{> tabs}}{{> mobile}}{{> toolbar}}{{> rooms}}</div>{{> modal}}',
rooms: '<div id="chat-rooms" class="rooms"></div>',
tabs: '<ul id="chat-tabs"></ul>',
mobileIcon: '<div id="mobile-roster-icon"><a class="box-shadow-icon"></a></div>',
tab: '<li class="roomtype-{{roomType}}" data-roomjid="{{roomJid}}" data-roomtype="{{roomType}}">' + '<a title="{{name}}" href="#" class="label">{{#privateUserChat}}@{{/privateUserChat}}{{name}}</a>' + '<a href="#" class="transition"></a><a href="#" class="close">×</a>' + '<small class="unread"></small></li>',
modal: '<div id="chat-modal"><a id="admin-message-cancel" class="close" href="#">×</a>' + '<span id="chat-modal-body"></span>' + '<img src="{{assetsPath}}img/modal-spinner.gif" id="chat-modal-spinner" />' + '</div><div id="chat-modal-overlay"></div>',
adminMessage: '<li><small data-timestamp="{{timestamp}}">{{time}}</small><div class="adminmessage">' + '<span class="label">{{sender}}</span>' + '<span class="spacer">▸</span>{{subject}} {{{message}}}</div></li>',
infoMessage: '<li><small data-timestamp="{{timestamp}}">{{time}}</small><div class="infomessage">' + '<span class="spacer">•</span>{{subject}} {{{message}}}</div></li>',
toolbar: '<ul id="chat-toolbar">' + '<li id="emoticons-icon" data-tooltip="{{tooltipEmoticons}}"></li>' + '<li id="chat-sound-control" class="checked" data-tooltip="{{tooltipSound}}"></li>' + '<li id="chat-autoscroll-control" class="checked" data-tooltip="{{tooltipAutoscroll}}"></li>' + '<li class="checked" id="chat-statusmessage-control" data-tooltip="{{tooltipStatusmessage}}">' + '</li><li class="context" data-tooltip="{{tooltipAdministration}}"></li>' + '<li class="usercount" data-tooltip="{{tooltipUsercount}}">' + '<span id="chat-usercount"></span></li></ul>',
Context: {
menu: '<div id="context-menu"><i class="arrow arrow-top"></i>' + '<ul></ul><i class="arrow arrow-bottom"></i></div>',
menulinks: '<li class="{{class}}" id="context-menu-{{id}}">{{label}}</li>',
contextModalForm: '<form action="#" id="context-modal-form">' + '<label for="context-modal-label">{{_label}}</label>' + '<input type="text" name="contextModalField" id="context-modal-field" />' + '<input type="submit" class="button" name="send" value="{{_submit}}" /></form>',
adminMessageReason: '<a id="admin-message-cancel" class="close" href="#">×</a>' + "<p>{{_action}}</p>{{#reason}}<p>{{_reason}}</p>{{/reason}}"
},
tooltip: '<div id="tooltip"><i class="arrow arrow-top"></i>' + '<div></div><i class="arrow arrow-bottom"></i></div>'
};
self.Room = {
pane: '<div class="room-pane roomtype-{{roomType}}" id="chat-room-{{roomId}}" data-roomjid="{{roomJid}}" data-roomtype="{{roomType}}">' + "{{> roster}}{{> messages}}{{> form}}</div>",
subject: '<li><small data-timestamp="{{timestamp}}">{{time}}</small><div class="subject">' + '<span class="label">{{roomName}}</span>' + '<span class="spacer">▸</span>{{_roomSubject}} {{{subject}}}</div></li>',
form: '<div class="message-form-wrapper">' + '<form method="post" class="message-form">' + '<input name="message" class="field" type="text" aria-label="Message Form Text Field" autocomplete="off" maxlength="1000" />' + '<input type="submit" class="submit" name="submit" value="{{_messageSubmit}}" /></form></div>'
};
self.Roster = {
pane: '<div class="roster-pane"></div>',
user: '<div class="user role-{{role}} affiliation-{{affiliation}}{{#me}} me{{/me}}"' + ' id="user-{{roomId}}-{{userId}}" data-jid="{{userJid}}" data-real-jid="{{realJid}}"' + ' data-nick="{{nick}}" data-role="{{role}}" data-affiliation="{{affiliation}}" data-status="{{status}}">' + '<div class="label">{{displayNick}}</div><ul>' + '<li class="context" id="context-{{roomId}}-{{userId}}">▾</li>' + '<li class="role role-{{role}} affiliation-{{affiliation}}" data-tooltip="{{tooltipRole}}"></li>' + '<li class="ignore" data-tooltip="{{tooltipIgnored}}"></li></ul></div>'
};
self.Message = {
pane: '<div class="message-pane-wrapper"><ul class="message-pane"></ul></div>',
item: '<li><small data-timestamp="{{timestamp}}">{{time}}</small><div>' + '<a class="label" href="#" class="name">{{displayName}}</a>' + '<span class="spacer">▸</span>{{{message}}}</div></li>'
};
self.Login = {
form: '<form method="post" id="login-form" class="login-form">' + '{{#displayNickname}}<label for="username">{{_labelNickname}}</label><input type="text" id="username" name="username"/>{{/displayNickname}}' + '{{#displayUsername}}<label for="username">{{_labelUsername}}</label>' + '<input type="text" id="username" name="username"/>' + '{{#displayDomain}} <span class="at-symbol">@</span> ' + '<select id="domain" name="domain">{{#domains}}<option value="{{domain}}">{{domain}}</option>{{/domains}}</select>' + "{{/displayDomain}}" + "{{/displayUsername}}" + '{{#presetJid}}<input type="hidden" id="username" name="username" value="{{presetJid}}"/>{{/presetJid}}' + '{{#displayPassword}}<label for="password">{{_labelPassword}}</label>' + '<input type="password" id="password" name="password" />{{/displayPassword}}' + '<input type="submit" class="button" value="{{_loginSubmit}}" /></form>'
};
self.PresenceError = {
enterPasswordForm: "<strong>{{_label}}</strong>" + '<form method="post" id="enter-password-form" class="enter-password-form">' + '<label for="password">{{_labelPassword}}</label><input type="password" id="password" name="password" />' + '<input type="submit" class="button" value="{{_joinSubmit}}" /></form>',
nicknameConflictForm: "<strong>{{_label}}</strong>" + '<form method="post" id="nickname-conflict-form" class="nickname-conflict-form">' + '<label for="nickname">{{_labelNickname}}</label><input type="text" id="nickname" name="nickname" />' + '<input type="submit" class="button" value="{{_loginSubmit}}" /></form>',
displayError: "<strong>{{_error}}</strong>"
};
return self;
}(Candy.View.Template || {});
/** File: translation.js
* Candy - Chats are not dead yet.
*
* Legal: See the LICENSE file at the top-level directory of this distribution and at https://github.com/candy-chat/candy/blob/master/LICENSE
*/
"use strict";
/* global Candy */
/** Class: Candy.View.Translation
* Contains translations
*/
Candy.View.Translation = {
en: {
status: "Status: %s",
statusConnecting: "Connecting...",
statusConnected: "Connected",
statusDisconnecting: "Disconnecting...",
statusDisconnected: "Disconnected",
statusAuthfail: "Authentication failed",
roomSubject: "Subject:",
messageSubmit: "Send",
labelUsername: "Username:",
labelNickname: "Nickname:",
labelPassword: "Password:",
loginSubmit: "Login",
loginInvalid: "Invalid JID",
reason: "Reason:",
subject: "Subject:",
reasonWas: "Reason was: %s.",
kickActionLabel: "Kick",
youHaveBeenKickedBy: "You have been kicked from %2$s by %1$s",
youHaveBeenKicked: "You have been kicked from %s",
banActionLabel: "Ban",
youHaveBeenBannedBy: "You have been banned from %1$s by %2$s",
youHaveBeenBanned: "You have been banned from %s",
privateActionLabel: "Private chat",
ignoreActionLabel: "Ignore",
unignoreActionLabel: "Unignore",
setSubjectActionLabel: "Change Subject",
administratorMessageSubject: "Administrator",
userJoinedRoom: "%s joined the room.",
userLeftRoom: "%s left the room.",
userHasBeenKickedFromRoom: "%s has been kicked from the room.",
userHasBeenBannedFromRoom: "%s has been banned from the room.",
userChangedNick: "%1$s is now known as %2$s.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderator",
tooltipIgnored: "You ignore this user",
tooltipEmoticons: "Emoticons",
tooltipSound: "Play sound for new private messages",
tooltipAutoscroll: "Autoscroll",
tooltipStatusmessage: "Display status messages",
tooltipAdministration: "Room Administration",
tooltipUsercount: "Room Occupants",
enterRoomPassword: 'Room "%s" is password protected.',
enterRoomPasswordSubmit: "Join room",
passwordEnteredInvalid: 'Invalid password for room "%s".',
nicknameConflict: "Username already in use. Please choose another one.",
errorMembersOnly: 'You can\'t join room "%s": Insufficient rights.',
errorMaxOccupantsReached: 'You can\'t join room "%s": Too many occupants.',
errorAutojoinMissing: "No autojoin parameter set in configuration. Please set one to continue.",
antiSpamMessage: "Please do not spam. You have been blocked for a short-time."
},
de: {
status: "Status: %s",
statusConnecting: "Verbinden...",
statusConnected: "Verbunden",
statusDisconnecting: "Verbindung trennen...",
statusDisconnected: "Verbindung getrennt",
statusAuthfail: "Authentifizierung fehlgeschlagen",
roomSubject: "Thema:",
messageSubmit: "Senden",
labelUsername: "Benutzername:",
labelNickname: "Spitzname:",
labelPassword: "Passwort:",
loginSubmit: "Anmelden",
loginInvalid: "Ungültige JID",
reason: "Begründung:",
subject: "Titel:",
reasonWas: "Begründung: %s.",
kickActionLabel: "Kick",
youHaveBeenKickedBy: "Du wurdest soeben aus dem Raum %1$s gekickt (%2$s)",
youHaveBeenKicked: "Du wurdest soeben aus dem Raum %s gekickt",
banActionLabel: "Ban",
youHaveBeenBannedBy: "Du wurdest soeben aus dem Raum %1$s verbannt (%2$s)",
youHaveBeenBanned: "Du wurdest soeben aus dem Raum %s verbannt",
privateActionLabel: "Privater Chat",
ignoreActionLabel: "Ignorieren",
unignoreActionLabel: "Nicht mehr ignorieren",
setSubjectActionLabel: "Thema ändern",
administratorMessageSubject: "Administrator",
userJoinedRoom: "%s hat soeben den Raum betreten.",
userLeftRoom: "%s hat soeben den Raum verlassen.",
userHasBeenKickedFromRoom: "%s ist aus dem Raum gekickt worden.",
userHasBeenBannedFromRoom: "%s ist aus dem Raum verbannt worden.",
userChangedNick: "%1$s hat den Nicknamen zu %2$s geändert.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderator",
tooltipIgnored: "Du ignorierst diesen Benutzer",
tooltipEmoticons: "Smileys",
tooltipSound: "Ton abspielen bei neuen privaten Nachrichten",
tooltipAutoscroll: "Autoscroll",
tooltipStatusmessage: "Statusnachrichten anzeigen",
tooltipAdministration: "Raum Administration",
tooltipUsercount: "Anzahl Benutzer im Raum",
enterRoomPassword: 'Raum "%s" ist durch ein Passwort geschützt.',
enterRoomPasswordSubmit: "Raum betreten",
passwordEnteredInvalid: 'Inkorrektes Passwort für Raum "%s".',
nicknameConflict: "Der Benutzername wird bereits verwendet. Bitte wähle einen anderen.",
errorMembersOnly: 'Du kannst den Raum "%s" nicht betreten: Ungenügende Rechte.',
errorMaxOccupantsReached: 'Du kannst den Raum "%s" nicht betreten: Benutzerlimit erreicht.',
errorAutojoinMissing: 'Keine "autojoin" Konfiguration gefunden. Bitte setze eine konfiguration um fortzufahren.',
antiSpamMessage: "Bitte nicht spammen. Du wurdest für eine kurze Zeit blockiert."
},
fr: {
status: "Status : %s",
statusConnecting: "Connexion…",
statusConnected: "Connecté",
statusDisconnecting: "Déconnexion…",
statusDisconnected: "Déconnecté",
statusAuthfail: "L’identification a échoué",
roomSubject: "Sujet :",
messageSubmit: "Envoyer",
labelUsername: "Nom d’utilisateur :",
labelNickname: "Pseudo :",
labelPassword: "Mot de passe :",
loginSubmit: "Connexion",
loginInvalid: "JID invalide",
reason: "Motif :",
subject: "Titre :",
reasonWas: "Motif : %s.",
kickActionLabel: "Kick",
youHaveBeenKickedBy: "Vous avez été expulsé du salon %1$s (%2$s)",
youHaveBeenKicked: "Vous avez été expulsé du salon %s",
banActionLabel: "Ban",
youHaveBeenBannedBy: "Vous avez été banni du salon %1$s (%2$s)",
youHaveBeenBanned: "Vous avez été banni du salon %s",
privateActionLabel: "Chat privé",
ignoreActionLabel: "Ignorer",
unignoreActionLabel: "Ne plus ignorer",
setSubjectActionLabel: "Changer le sujet",
administratorMessageSubject: "Administrateur",
userJoinedRoom: "%s vient d’entrer dans le salon.",
userLeftRoom: "%s vient de quitter le salon.",
userHasBeenKickedFromRoom: "%s a été expulsé du salon.",
userHasBeenBannedFromRoom: "%s a été banni du salon.",
dateFormat: "dd/mm/yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Modérateur",
tooltipIgnored: "Vous ignorez cette personne",
tooltipEmoticons: "Smileys",
tooltipSound: "Jouer un son lors de la réception de messages privés",
tooltipAutoscroll: "Défilement automatique",
tooltipStatusmessage: "Afficher les changements d’état",
tooltipAdministration: "Administration du salon",
tooltipUsercount: "Nombre d’utilisateurs dans le salon",
enterRoomPassword: "Le salon %s est protégé par un mot de passe.",
enterRoomPasswordSubmit: "Entrer dans le salon",
passwordEnteredInvalid: "Le mot de passe pour le salon %s est invalide.",
nicknameConflict: "Ce nom d’utilisateur est déjà utilisé. Veuillez en choisir un autre.",
errorMembersOnly: "Vous ne pouvez pas entrer dans le salon %s : droits insuffisants.",
errorMaxOccupantsReached: "Vous ne pouvez pas entrer dans le salon %s : limite d’utilisateurs atteinte.",
antiSpamMessage: "Merci de ne pas spammer. Vous avez été bloqué pendant une courte période."
},
nl: {
status: "Status: %s",
statusConnecting: "Verbinding maken...",
statusConnected: "Verbinding is gereed",
statusDisconnecting: "Verbinding verbreken...",
statusDisconnected: "Verbinding is verbroken",
statusAuthfail: "Authenticatie is mislukt",
roomSubject: "Onderwerp:",
messageSubmit: "Verstuur",
labelUsername: "Gebruikersnaam:",
labelPassword: "Wachtwoord:",
loginSubmit: "Inloggen",
loginInvalid: "JID is onjuist",
reason: "Reden:",
subject: "Onderwerp:",
reasonWas: "De reden was: %s.",
kickActionLabel: "Verwijderen",
youHaveBeenKickedBy: "Je bent verwijderd van %1$s door %2$s",
youHaveBeenKicked: "Je bent verwijderd van %s",
banActionLabel: "Blokkeren",
youHaveBeenBannedBy: "Je bent geblokkeerd van %1$s door %2$s",
youHaveBeenBanned: "Je bent geblokkeerd van %s",
privateActionLabel: "Prive gesprek",
ignoreActionLabel: "Negeren",
unignoreActionLabel: "Niet negeren",
setSubjectActionLabel: "Onderwerp wijzigen",
administratorMessageSubject: "Beheerder",
userJoinedRoom: "%s komt de chat binnen.",
userLeftRoom: "%s heeft de chat verlaten.",
userHasBeenKickedFromRoom: "%s is verwijderd.",
userHasBeenBannedFromRoom: "%s is geblokkeerd.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderator",
tooltipIgnored: "Je negeert deze gebruiker",
tooltipEmoticons: "Emotie-iconen",
tooltipSound: "Speel een geluid af bij nieuwe privé berichten.",
tooltipAutoscroll: "Automatisch scrollen",
tooltipStatusmessage: "Statusberichten weergeven",
tooltipAdministration: "Instellingen",
tooltipUsercount: "Gebruikers",
enterRoomPassword: 'De Chatroom "%s" is met een wachtwoord beveiligd.',
enterRoomPasswordSubmit: "Ga naar Chatroom",
passwordEnteredInvalid: 'Het wachtwoord voor de Chatroom "%s" is onjuist.',
nicknameConflict: "De gebruikersnaam is reeds in gebruik. Probeer a.u.b. een andere gebruikersnaam.",
errorMembersOnly: 'Je kunt niet deelnemen aan de Chatroom "%s": Je hebt onvoldoende rechten.',
errorMaxOccupantsReached: 'Je kunt niet deelnemen aan de Chatroom "%s": Het maximum aantal gebruikers is bereikt.',
antiSpamMessage: "Het is niet toegestaan om veel berichten naar de server te versturen. Je bent voor een korte periode geblokkeerd."
},
es: {
status: "Estado: %s",
statusConnecting: "Conectando...",
statusConnected: "Conectado",
statusDisconnecting: "Desconectando...",
statusDisconnected: "Desconectado",
statusAuthfail: "Falló la autenticación",
roomSubject: "Asunto:",
messageSubmit: "Enviar",
labelUsername: "Usuario:",
labelPassword: "Clave:",
loginSubmit: "Entrar",
loginInvalid: "JID no válido",
reason: "Razón:",
subject: "Asunto:",
reasonWas: "La razón fue: %s.",
kickActionLabel: "Expulsar",
youHaveBeenKickedBy: "Has sido expulsado de %1$s por %2$s",
youHaveBeenKicked: "Has sido expulsado de %s",
banActionLabel: "Prohibir",
youHaveBeenBannedBy: "Has sido expulsado permanentemente de %1$s por %2$s",
youHaveBeenBanned: "Has sido expulsado permanentemente de %s",
privateActionLabel: "Chat privado",
ignoreActionLabel: "Ignorar",
unignoreActionLabel: "No ignorar",
setSubjectActionLabel: "Cambiar asunto",
administratorMessageSubject: "Administrador",
userJoinedRoom: "%s se ha unido a la sala.",
userLeftRoom: "%s ha dejado la sala.",
userHasBeenKickedFromRoom: "%s ha sido expulsado de la sala.",
userHasBeenBannedFromRoom: "%s ha sido expulsado permanentemente de la sala.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderador",
tooltipIgnored: "Ignoras a éste usuario",
tooltipEmoticons: "Emoticonos",
tooltipSound: "Reproducir un sonido para nuevos mensajes privados",
tooltipAutoscroll: "Desplazamiento automático",
tooltipStatusmessage: "Mostrar mensajes de estado",
tooltipAdministration: "Administración de la sala",
tooltipUsercount: "Usuarios en la sala",
enterRoomPassword: 'La sala "%s" está protegida mediante contraseña.',
enterRoomPasswordSubmit: "Unirse a la sala",
passwordEnteredInvalid: 'Contraseña incorrecta para la sala "%s".',
nicknameConflict: "El nombre de usuario ya está siendo utilizado. Por favor elija otro.",
errorMembersOnly: 'No se puede unir a la sala "%s": no tiene privilegios suficientes.',
errorMaxOccupantsReached: 'No se puede unir a la sala "%s": demasiados participantes.',
antiSpamMessage: "Por favor, no hagas spam. Has sido bloqueado temporalmente."
},
cn: {
status: "状态: %s",
statusConnecting: "连接中...",
statusConnected: "已连接",
statusDisconnecting: "断开连接中...",
statusDisconnected: "已断开连接",
statusAuthfail: "认证失败",
roomSubject: "主题:",
messageSubmit: "发送",
labelUsername: "用户名:",
labelPassword: "密码:",
loginSubmit: "登录",
loginInvalid: "用户名不合法",
reason: "原因:",
subject: "主题:",
reasonWas: "原因是: %s.",
kickActionLabel: "踢除",
youHaveBeenKickedBy: "你在 %1$s 被管理者 %2$s 请出房间",
banActionLabel: "禁言",
youHaveBeenBannedBy: "你在 %1$s 被管理者 %2$s 禁言",
privateActionLabel: "单独对话",
ignoreActionLabel: "忽略",
unignoreActionLabel: "不忽略",
setSubjectActionLabel: "变更主题",
administratorMessageSubject: "管理员",
userJoinedRoom: "%s 加入房间",
userLeftRoom: "%s 离开房间",
userHasBeenKickedFromRoom: "%s 被请出这个房间",
userHasBeenBannedFromRoom: "%s 被管理者禁言",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "管理",
tooltipIgnored: "你忽略了这个会员",
tooltipEmoticons: "表情",
tooltipSound: "新消息发音",
tooltipAutoscroll: "滚动条",
tooltipStatusmessage: "禁用状态消息",
tooltipAdministration: "房间管理",
tooltipUsercount: "房间占有者",
enterRoomPassword: '登录房间 "%s" 需要密码.',
enterRoomPasswordSubmit: "加入房间",
passwordEnteredInvalid: '登录房间 "%s" 的密码不正确',
nicknameConflict: "用户名已经存在,请另选一个",
errorMembersOnly: '您的权限不够,不能登录房间 "%s" ',
errorMaxOccupantsReached: '房间 "%s" 的人数已达上限,您不能登录',
antiSpamMessage: "因为您在短时间内发送过多的消息 服务器要阻止您一小段时间。"
},
ja: {
status: "ステータス: %s",
statusConnecting: "接続中…",
statusConnected: "接続されました",
statusDisconnecting: "ディスコネクト中…",
statusDisconnected: "ディスコネクトされました",
statusAuthfail: "認証に失敗しました",
roomSubject: "トピック:",
messageSubmit: "送信",
labelUsername: "ユーザーネーム:",
labelPassword: "パスワード:",
loginSubmit: "ログイン",
loginInvalid: "ユーザーネームが正しくありません",
reason: "理由:",
subject: "トピック:",
reasonWas: "理由: %s。",
kickActionLabel: "キック",
youHaveBeenKickedBy: "あなたは%2$sにより%1$sからキックされました。",
youHaveBeenKicked: "あなたは%sからキックされました。",
banActionLabel: "アカウントバン",
youHaveBeenBannedBy: "あなたは%2$sにより%1$sからアカウントバンされました。",
youHaveBeenBanned: "あなたは%sからアカウントバンされました。",
privateActionLabel: "プライベートメッセージ",
ignoreActionLabel: "無視する",
unignoreActionLabel: "無視をやめる",
setSubjectActionLabel: "トピックを変える",
administratorMessageSubject: "管理者",
userJoinedRoom: "%sは入室しました。",
userLeftRoom: "%sは退室しました。",
userHasBeenKickedFromRoom: "%sは部屋からキックされました。",
userHasBeenBannedFromRoom: "%sは部屋からアカウントバンされました。",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "モデレーター",
tooltipIgnored: "このユーザーを無視設定にしている",
tooltipEmoticons: "絵文字",
tooltipSound: "新しいメッセージが届くたびに音を鳴らす",
tooltipAutoscroll: "オートスクロール",
tooltipStatusmessage: "ステータスメッセージを表示",
tooltipAdministration: "部屋の管理",
tooltipUsercount: "この部屋の参加者の数",
enterRoomPassword: '"%s"の部屋に入るにはパスワードが必要です。',
enterRoomPasswordSubmit: "部屋に入る",
passwordEnteredInvalid: '"%s"のパスワードと異なるパスワードを入力しました。',
nicknameConflict: "このユーザーネームはすでに利用されているため、別のユーザーネームを選んでください。",
errorMembersOnly: '"%s"の部屋に入ることができません: 利用権限を満たしていません。',
errorMaxOccupantsReached: '"%s"の部屋に入ることができません: 参加者の数はすでに上限に達しました。',
antiSpamMessage: "スパムなどの行為はやめてください。あなたは一時的にブロックされました。"
},
sv: {
status: "Status: %s",
statusConnecting: "Ansluter...",
statusConnected: "Ansluten",
statusDisconnecting: "Kopplar från...",
statusDisconnected: "Frånkopplad",
statusAuthfail: "Autentisering misslyckades",
roomSubject: "Ämne:",
messageSubmit: "Skicka",
labelUsername: "Användarnamn:",
labelPassword: "Lösenord:",
loginSubmit: "Logga in",
loginInvalid: "Ogiltigt JID",
reason: "Anledning:",
subject: "Ämne:",
reasonWas: "Anledningen var: %s.",
kickActionLabel: "Sparka ut",
youHaveBeenKickedBy: "Du har blivit utsparkad från %2$s av %1$s",
youHaveBeenKicked: "Du har blivit utsparkad från %s",
banActionLabel: "Bannlys",
youHaveBeenBannedBy: "Du har blivit bannlyst från %1$s av %2$s",
youHaveBeenBanned: "Du har blivit bannlyst från %s",
privateActionLabel: "Privat chatt",
ignoreActionLabel: "Blockera",
unignoreActionLabel: "Avblockera",
setSubjectActionLabel: "Ändra ämne",
administratorMessageSubject: "Administratör",
userJoinedRoom: "%s kom in i rummet.",
userLeftRoom: "%s har lämnat rummet.",
userHasBeenKickedFromRoom: "%s har blivit utsparkad ur rummet.",
userHasBeenBannedFromRoom: "%s har blivit bannlyst från rummet.",
dateFormat: "yyyy-mm-dd",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderator",
tooltipIgnored: "Du blockerar denna användare",
tooltipEmoticons: "Smilies",
tooltipSound: "Spela upp ett ljud vid nytt privat meddelande",
tooltipAutoscroll: "Autoskrolla",
tooltipStatusmessage: "Visa statusmeddelanden",
tooltipAdministration: "Rumadministrering",
tooltipUsercount: "Antal användare i rummet",
enterRoomPassword: 'Rummet "%s" är lösenordsskyddat.',
enterRoomPasswordSubmit: "Anslut till rum",
passwordEnteredInvalid: 'Ogiltigt lösenord för rummet "%s".',
nicknameConflict: "Upptaget användarnamn. Var god välj ett annat.",
errorMembersOnly: 'Du kan inte ansluta till rummet "%s": Otillräckliga rättigheter.',
errorMaxOccupantsReached: 'Du kan inte ansluta till rummet "%s": Rummet är fullt.',
antiSpamMessage: "Var god avstå från att spamma. Du har blivit blockerad för en kort stund."
},
fi: {
status: "Status: %s",
statusConnecting: "Muodostetaan yhteyttä...",
statusConnected: "Yhdistetty",
statusDisconnecting: "Katkaistaan yhteyttä...",
statusDisconnected: "Yhteys katkaistu",
statusAuthfail: "Autentikointi epäonnistui",
roomSubject: "Otsikko:",
messageSubmit: "Lähetä",
labelUsername: "Käyttäjätunnus:",
labelNickname: "Nimimerkki:",
labelPassword: "Salasana:",
loginSubmit: "Kirjaudu sisään",
loginInvalid: "Virheellinen JID",
reason: "Syy:",
subject: "Otsikko:",
reasonWas: "Syy oli: %s.",
kickActionLabel: "Potkaise",
youHaveBeenKickedBy: "Nimimerkki %1$s potkaisi sinut pois huoneesta %2$s",
youHaveBeenKicked: "Sinut potkaistiin pois huoneesta %s",
banActionLabel: "Porttikielto",
youHaveBeenBannedBy: "Nimimerkki %2$s antoi sinulle porttikiellon huoneeseen %1$s",
youHaveBeenBanned: "Sinulle on annettu porttikielto huoneeseen %s",
privateActionLabel: "Yksityinen keskustelu",
ignoreActionLabel: "Hiljennä",
unignoreActionLabel: "Peruuta hiljennys",
setSubjectActionLabel: "Vaihda otsikkoa",
administratorMessageSubject: "Ylläpitäjä",
userJoinedRoom: "%s tuli huoneeseen.",
userLeftRoom: "%s lähti huoneesta.",
userHasBeenKickedFromRoom: "%s potkaistiin pois huoneesta.",
userHasBeenBannedFromRoom: "%s sai porttikiellon huoneeseen.",
userChangedNick: "%1$s vaihtoi nimimerkikseen %2$s.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Ylläpitäjä",
tooltipIgnored: "Olet hiljentänyt tämän käyttäjän",
tooltipEmoticons: "Hymiöt",
tooltipSound: "Soita äänimerkki uusista yksityisviesteistä",
tooltipAutoscroll: "Automaattinen vieritys",
tooltipStatusmessage: "Näytä statusviestit",
tooltipAdministration: "Huoneen ylläpito",
tooltipUsercount: "Huoneen jäsenet",
enterRoomPassword: 'Huone "%s" on suojattu salasanalla.',
enterRoomPasswordSubmit: "Liity huoneeseen",
passwordEnteredInvalid: 'Virheelinen salasana huoneeseen "%s".',
nicknameConflict: "Käyttäjätunnus oli jo käytössä. Valitse jokin toinen käyttäjätunnus.",
errorMembersOnly: 'Et voi liittyä huoneeseen "%s": ei oikeuksia.',
errorMaxOccupantsReached: 'Et voi liittyä huoneeseen "%s": liian paljon jäseniä.',
errorAutojoinMissing: 'Parametria "autojoin" ei ole määritelty asetuksissa. Tee määrittely jatkaaksesi.',
antiSpamMessage: "Ethän spämmää. Sinut on nyt väliaikaisesti pistetty jäähylle."
},
it: {
status: "Stato: %s",
statusConnecting: "Connessione...",
statusConnected: "Connessione",
statusDisconnecting: "Disconnessione...",
statusDisconnected: "Disconnesso",
statusAuthfail: "Autenticazione fallita",
roomSubject: "Oggetto:",
messageSubmit: "Invia",
labelUsername: "Nome utente:",
labelPassword: "Password:",
loginSubmit: "Login",
loginInvalid: "JID non valido",
reason: "Ragione:",
subject: "Oggetto:",
reasonWas: "Ragione precedente: %s.",
kickActionLabel: "Espelli",
youHaveBeenKickedBy: "Sei stato espulso da %2$s da %1$s",
youHaveBeenKicked: "Sei stato espulso da %s",
banActionLabel: "Escluso",
youHaveBeenBannedBy: "Sei stato escluso da %1$s da %2$s",
youHaveBeenBanned: "Sei stato escluso da %s",
privateActionLabel: "Stanza privata",
ignoreActionLabel: "Ignora",
unignoreActionLabel: "Non ignorare",
setSubjectActionLabel: "Cambia oggetto",
administratorMessageSubject: "Amministratore",
userJoinedRoom: "%s si è unito alla stanza.",
userLeftRoom: "%s ha lasciato la stanza.",
userHasBeenKickedFromRoom: "%s è stato espulso dalla stanza.",
userHasBeenBannedFromRoom: "%s è stato escluso dalla stanza.",
dateFormat: "dd/mm/yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderatore",
tooltipIgnored: "Stai ignorando questo utente",
tooltipEmoticons: "Emoticons",
tooltipSound: "Riproduci un suono quando arrivano messaggi privati",
tooltipAutoscroll: "Autoscroll",
tooltipStatusmessage: "Mostra messaggi di stato",
tooltipAdministration: "Amministrazione stanza",
tooltipUsercount: "Partecipanti alla stanza",
enterRoomPassword: 'La stanza "%s" è protetta da password.',
enterRoomPasswordSubmit: "Unisciti alla stanza",
passwordEnteredInvalid: 'Password non valida per la stanza "%s".',
nicknameConflict: "Nome utente già in uso. Scegline un altro.",
errorMembersOnly: 'Non puoi unirti alla stanza "%s": Permessi insufficienti.',
errorMaxOccupantsReached: 'Non puoi unirti alla stanza "%s": Troppi partecipanti.',
antiSpamMessage: "Per favore non scrivere messaggi pubblicitari. Sei stato bloccato per un po' di tempo."
},
pl: {
status: "Status: %s",
statusConnecting: "Łączę...",
statusConnected: "Połączone",
statusDisconnecting: "Rozłączam...",
statusDisconnected: "Rozłączone",
statusAuthfail: "Nieprawidłowa autoryzacja",
roomSubject: "Temat:",
messageSubmit: "Wyślij",
labelUsername: "Nazwa użytkownika:",
labelNickname: "Ksywka:",
labelPassword: "Hasło:",
loginSubmit: "Zaloguj",
loginInvalid: "Nieprawidłowy JID",
reason: "Przyczyna:",
subject: "Temat:",
reasonWas: "Z powodu: %s.",
kickActionLabel: "Wykop",
youHaveBeenKickedBy: "Zostałeś wykopany z %2$s przez %1$s",
youHaveBeenKicked: "Zostałeś wykopany z %s",
banActionLabel: "Ban",
youHaveBeenBannedBy: "Zostałeś zbanowany na %1$s przez %2$s",
youHaveBeenBanned: "Zostałeś zbanowany na %s",
privateActionLabel: "Rozmowa prywatna",
ignoreActionLabel: "Zignoruj",
unignoreActionLabel: "Przestań ignorować",
setSubjectActionLabel: "Zmień temat",
administratorMessageSubject: "Administrator",
userJoinedRoom: "%s wszedł do pokoju.",
userLeftRoom: "%s opuścił pokój.",
userHasBeenKickedFromRoom: "%s został wykopany z pokoju.",
userHasBeenBannedFromRoom: "%s został zbanowany w pokoju.",
userChangedNick: "%1$s zmienił ksywkę na %2$s.",
presenceUnknownWarningSubject: "Uwaga:",
presenceUnknownWarning: "Rozmówca może nie być połączony. Nie możemy ustalić jego obecności.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderator",
tooltipIgnored: "Ignorujesz tego rozmówcę",
tooltipEmoticons: "Emoty",
tooltipSound: "Sygnał dźwiękowy przy otrzymaniu wiadomości",
tooltipAutoscroll: "Autoprzewijanie",
tooltipStatusmessage: "Wyświetl statusy",
tooltipAdministration: "Administrator pokoju",
tooltipUsercount: "Obecni rozmówcy",
enterRoomPassword: 'Pokój "%s" wymaga hasła.',
enterRoomPasswordSubmit: "Wejdź do pokoju",
passwordEnteredInvalid: 'Niewłaściwie hasło do pokoju "%s".',
nicknameConflict: "Nazwa w użyciu. Wybierz inną.",
errorMembersOnly: 'Nie możesz wejść do pokoju "%s": Niepełne uprawnienia.',
errorMaxOccupantsReached: 'Nie możesz wejść do pokoju "%s": Siedzi w nim zbyt wielu ludzi.',
errorAutojoinMissing: "Konfiguracja nie zawiera parametru automatycznego wejścia do pokoju. Wskaż pokój do którego chcesz wejść.",
antiSpamMessage: "Please do not spam. You have been blocked for a short-time."
},
pt: {
status: "Status: %s",
statusConnecting: "Conectando...",
statusConnected: "Conectado",
statusDisconnecting: "Desligando...",
statusDisconnected: "Desligado",
statusAuthfail: "Falha na autenticação",
roomSubject: "Assunto:",
messageSubmit: "Enviar",
labelUsername: "Usuário:",
labelPassword: "Senha:",
loginSubmit: "Entrar",
loginInvalid: "JID inválido",
reason: "Motivo:",
subject: "Assunto:",
reasonWas: "O motivo foi: %s.",
kickActionLabel: "Excluir",
youHaveBeenKickedBy: "Você foi excluido de %1$s por %2$s",
youHaveBeenKicked: "Você foi excluido de %s",
banActionLabel: "Bloquear",
youHaveBeenBannedBy: "Você foi excluido permanentemente de %1$s por %2$s",
youHaveBeenBanned: "Você foi excluido permanentemente de %s",
privateActionLabel: "Bate-papo privado",
ignoreActionLabel: "Ignorar",
unignoreActionLabel: "Não ignorar",
setSubjectActionLabel: "Trocar Assunto",
administratorMessageSubject: "Administrador",
userJoinedRoom: "%s entrou na sala.",
userLeftRoom: "%s saiu da sala.",
userHasBeenKickedFromRoom: "%s foi excluido da sala.",
userHasBeenBannedFromRoom: "%s foi excluido permanentemente da sala.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderador",
tooltipIgnored: "Você ignora este usuário",
tooltipEmoticons: "Emoticons",
tooltipSound: "Reproduzir o som para novas mensagens privados",
tooltipAutoscroll: "Deslocamento automático",
tooltipStatusmessage: "Mostrar mensagens de status",
tooltipAdministration: "Administração da sala",
tooltipUsercount: "Usuários na sala",
enterRoomPassword: 'A sala "%s" é protegida por senha.',
enterRoomPasswordSubmit: "Junte-se à sala",
passwordEnteredInvalid: 'Senha incorreta para a sala "%s".',
nicknameConflict: "O nome de usuário já está em uso. Por favor, escolha outro.",
errorMembersOnly: 'Você não pode participar da sala "%s": privilégios insuficientes.',
errorMaxOccupantsReached: 'Você não pode participar da sala "%s": muitos participantes.',
antiSpamMessage: "Por favor, não envie spam. Você foi bloqueado temporariamente."
},
pt_br: {
status: "Estado: %s",
statusConnecting: "Conectando...",
statusConnected: "Conectado",
statusDisconnecting: "Desconectando...",
statusDisconnected: "Desconectado",
statusAuthfail: "Autenticação falhou",
roomSubject: "Assunto:",
messageSubmit: "Enviar",
labelUsername: "Usuário:",
labelPassword: "Senha:",
loginSubmit: "Entrar",
loginInvalid: "JID inválido",
reason: "Motivo:",
subject: "Assunto:",
reasonWas: "Motivo foi: %s.",
kickActionLabel: "Derrubar",
youHaveBeenKickedBy: "Você foi derrubado de %2$s por %1$s",
youHaveBeenKicked: "Você foi derrubado de %s",
banActionLabel: "Banir",
youHaveBeenBannedBy: "Você foi banido de %1$s por %2$s",
youHaveBeenBanned: "Você foi banido de %s",
privateActionLabel: "Conversa privada",
ignoreActionLabel: "Ignorar",
unignoreActionLabel: "Não ignorar",
setSubjectActionLabel: "Mudar Assunto",
administratorMessageSubject: "Administrador",
userJoinedRoom: "%s entrou na sala.",
userLeftRoom: "%s saiu da sala.",
userHasBeenKickedFromRoom: "%s foi derrubado da sala.",
userHasBeenBannedFromRoom: "%s foi banido da sala.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderador",
tooltipIgnored: "Você ignora este usuário",
tooltipEmoticons: "Emoticons",
tooltipSound: "Tocar som para novas mensagens privadas",
tooltipAutoscroll: "Auto-rolagem",
tooltipStatusmessage: "Exibir mensagens de estados",
tooltipAdministration: "Administração de Sala",
tooltipUsercount: "Participantes da Sala",
enterRoomPassword: 'Sala "%s" é protegida por senha.',
enterRoomPasswordSubmit: "Entrar na sala",
passwordEnteredInvalid: 'Senha inváida para sala "%s".',
nicknameConflict: "Nome de usuário já em uso. Por favor escolha outro.",
errorMembersOnly: 'Você não pode entrar na sala "%s": privilégios insuficientes.',
errorMaxOccupantsReached: 'Você não pode entrar na sala "%s": máximo de participantes atingido.',
antiSpamMessage: "Por favor, não faça spam. Você foi bloqueado temporariamente."
},
ru: {
status: "Статус: %s",
statusConnecting: "Подключение...",
statusConnected: "Подключено",
statusDisconnecting: "Отключение...",
statusDisconnected: "Отключено",
statusAuthfail: "Неверный логин",
roomSubject: "Топик:",
messageSubmit: "Послать",
labelUsername: "Имя:",
labelNickname: "Ник:",
labelPassword: "Пароль:",
loginSubmit: "Логин",
loginInvalid: "Неверный JID",
reason: "Причина:",
subject: "Топик:",
reasonWas: "Причина была: %s.",
kickActionLabel: "Выбросить",
youHaveBeenKickedBy: "Пользователь %1$s выбросил вас из чата %2$s",
youHaveBeenKicked: "Вас выбросили из чата %s",
banActionLabel: "Запретить доступ",
youHaveBeenBannedBy: "Пользователь %1$s запретил вам доступ в чат %2$s",
youHaveBeenBanned: "Вам запретили доступ в чат %s",
privateActionLabel: "Один-на-один чат",
ignoreActionLabel: "Игнорировать",
unignoreActionLabel: "Отменить игнорирование",
setSubjectActionLabel: "Изменить топик",
administratorMessageSubject: "Администратор",
userJoinedRoom: "%s вошёл в чат.",
userLeftRoom: "%s вышел из чата.",
userHasBeenKickedFromRoom: "%s выброшен из чата.",
userHasBeenBannedFromRoom: "%s запрещён доступ в чат.",
userChangedNick: "%1$s сменил имя на %2$s.",
presenceUnknownWarningSubject: "Уведомление:",
presenceUnknownWarning: "Этот пользователь вероятнее всего оффлайн.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Модератор",
tooltipIgnored: "Вы игнорируете этого пользователя.",
tooltipEmoticons: "Смайлики",
tooltipSound: "Озвучивать новое частное сообщение",
tooltipAutoscroll: "Авто-прокручивание",
tooltipStatusmessage: "Показывать статус сообщения",
tooltipAdministration: "Администрирование чат комнаты",
tooltipUsercount: "Участники чата",
enterRoomPassword: 'Чат комната "%s" защищена паролем.',
enterRoomPasswordSubmit: "Войти в чат",
passwordEnteredInvalid: 'Неверный пароль для комнаты "%s".',
nicknameConflict: "Это имя уже используется. Пожалуйста выберите другое имя.",
errorMembersOnly: 'Вы не можете войти в чат "%s": Недостаточно прав доступа.',
errorMaxOccupantsReached: 'Вы не можете войти в чат "%s": Слишком много участников.',
errorAutojoinMissing: "Параметры автовхода не устновлены. Настройте их для продолжения.",
antiSpamMessage: "Пожалуйста не рассылайте спам. Вас заблокировали на короткое время."
},
ca: {
status: "Estat: %s",
statusConnecting: "Connectant...",
statusConnected: "Connectat",
statusDisconnecting: "Desconnectant...",
statusDisconnected: "Desconnectat",
statusAuthfail: "Ha fallat la autenticació",
roomSubject: "Assumpte:",
messageSubmit: "Enviar",
labelUsername: "Usuari:",
labelPassword: "Clau:",
loginSubmit: "Entrar",
loginInvalid: "JID no vàlid",
reason: "Raó:",
subject: "Assumpte:",
reasonWas: "La raó ha estat: %s.",
kickActionLabel: "Expulsar",
youHaveBeenKickedBy: "Has estat expulsat de %1$s per %2$s",
youHaveBeenKicked: "Has estat expulsat de %s",
banActionLabel: "Prohibir",
youHaveBeenBannedBy: "Has estat expulsat permanentment de %1$s per %2$s",
youHaveBeenBanned: "Has estat expulsat permanentment de %s",
privateActionLabel: "Xat privat",
ignoreActionLabel: "Ignorar",
unignoreActionLabel: "No ignorar",
setSubjectActionLabel: "Canviar assumpte",
administratorMessageSubject: "Administrador",
userJoinedRoom: "%s ha entrat a la sala.",
userLeftRoom: "%s ha deixat la sala.",
userHasBeenKickedFromRoom: "%s ha estat expulsat de la sala.",
userHasBeenBannedFromRoom: "%s ha estat expulsat permanentment de la sala.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderador",
tooltipIgnored: "Estàs ignorant aquest usuari",
tooltipEmoticons: "Emoticones",
tooltipSound: "Reproduir un so per a nous missatges",
tooltipAutoscroll: "Desplaçament automàtic",
tooltipStatusmessage: "Mostrar missatges d'estat",
tooltipAdministration: "Administració de la sala",
tooltipUsercount: "Usuaris dins la sala",
enterRoomPassword: 'La sala "%s" està protegida amb contrasenya.',
enterRoomPasswordSubmit: "Entrar a la sala",
passwordEnteredInvalid: 'Contrasenya incorrecta per a la sala "%s".',
nicknameConflict: "El nom d'usuari ja s'està utilitzant. Si us plau, escolleix-ne un altre.",
errorMembersOnly: 'No pots unir-te a la sala "%s": no tens prous privilegis.',
errorMaxOccupantsReached: 'No pots unir-te a la sala "%s": hi ha masses participants.',
antiSpamMessage: "Si us plau, no facis spam. Has estat bloquejat temporalment."
},
cs: {
status: "Stav: %s",
statusConnecting: "Připojování...",
statusConnected: "Připojeno",
statusDisconnecting: "Odpojování...",
statusDisconnected: "Odpojeno",
statusAuthfail: "Přihlášení selhalo",
roomSubject: "Předmět:",
messageSubmit: "Odeslat",
labelUsername: "Už. jméno:",
labelNickname: "Přezdívka:",
labelPassword: "Heslo:",
loginSubmit: "Přihlásit se",
loginInvalid: "Neplatné JID",
reason: "Důvod:",
subject: "Předmět:",
reasonWas: "Důvod byl: %s.",
kickActionLabel: "Vykopnout",
youHaveBeenKickedBy: "Byl jsi vyloučen z %2$s uživatelem %1$s",
youHaveBeenKicked: "Byl jsi vyloučen z %s",
banActionLabel: "Ban",
youHaveBeenBannedBy: "Byl jsi trvale vyloučen z %1$s uživatelem %2$s",
youHaveBeenBanned: "Byl jsi trvale vyloučen z %s",
privateActionLabel: "Soukromý chat",
ignoreActionLabel: "Ignorovat",
unignoreActionLabel: "Neignorovat",
setSubjectActionLabel: "Změnit předmět",
administratorMessageSubject: "Adminitrátor",
userJoinedRoom: "%s vešel do místnosti.",
userLeftRoom: "%s opustil místnost.",
userHasBeenKickedFromRoom: "%s byl vyloučen z místnosti.",
userHasBeenBannedFromRoom: "%s byl trvale vyloučen z místnosti.",
userChangedNick: "%1$s si změnil přezdívku na %2$s.",
presenceUnknownWarningSubject: "Poznámka:",
presenceUnknownWarning: "Tento uživatel může být offiline. Nemůžeme sledovat jeho přítmonost..",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "Moderátor",
tooltipIgnored: "Tento uživatel je ignorován",
tooltipEmoticons: "Emotikony",
tooltipSound: "Přehrát zvuk při nové soukromé zprávě",
tooltipAutoscroll: "Automaticky rolovat",
tooltipStatusmessage: "Zobrazovat stavové zprávy",
tooltipAdministration: "Správa místnosti",
tooltipUsercount: "Uživatelé",
enterRoomPassword: 'Místnost "%s" je chráněna heslem.',
enterRoomPasswordSubmit: "Připojit se do místnosti",
passwordEnteredInvalid: 'Neplatné heslo pro místnost "%s".',
nicknameConflict: "Takové přihlašovací jméno je již použito. Vyberte si prosím jiné.",
errorMembersOnly: 'Nemůžete se připojit do místnosti "%s": Nedostatečné oprávnění.',
errorMaxOccupantsReached: 'Nemůžete se připojit do místnosti "%s": Příliš mnoho uživatelů.',
errorAutojoinMissing: "Není nastaven parametr autojoin. Nastavte jej prosím.",
antiSpamMessage: "Nespamujte prosím. Váš účet byl na chvilku zablokován."
},
he: {
status: "מצב: %s",
statusConnecting: "כעת מתחבר...",
statusConnected: "מחובר",
statusDisconnecting: "כעת מתנתק...",
statusDisconnected: "מנותק",
statusAuthfail: "אימות נכשל",
roomSubject: "נושא:",
messageSubmit: "שלח",
labelUsername: "שם משתמש:",
labelNickname: "שם כינוי:",
labelPassword: "סיסמה:",
loginSubmit: "כניסה",
loginInvalid: "JID לא תקני",
reason: "סיבה:",
subject: "נושא:",
reasonWas: "סיבה היתה: %s.",
kickActionLabel: "בעט",
youHaveBeenKickedBy: "נבעטת מתוך %2$s על ידי %1$s",
youHaveBeenKicked: "נבעטת מתוך %s",
banActionLabel: "אסור",
youHaveBeenBannedBy: "נאסרת מתוך %1$s על ידי %2$s",
youHaveBeenBanned: "נאסרת מתוך %s",
privateActionLabel: "שיחה פרטית",
ignoreActionLabel: "התעלם",
unignoreActionLabel: "בטל התעלמות",
setSubjectActionLabel: "שנה נושא",
administratorMessageSubject: "מנהל",
userJoinedRoom: "%s נכנס(ה) לחדר.",
userLeftRoom: "%s עזב(ה) את החדר.",
userHasBeenKickedFromRoom: "%s נבעט(ה) מתוך החדר.",
userHasBeenBannedFromRoom: "%s נאסר(ה) מתוך החדר.",
userChangedNick: "%1$s מוכר(ת) כעת בתור %2$s.",
dateFormat: "dd.mm.yyyy",
timeFormat: "HH:MM:ss",
tooltipRole: "אחראי",
tooltipIgnored: "אתה מתעלם ממשתמש זה",
tooltipEmoticons: "רגשונים",
tooltipSound: "נגן צליל עבור הודעות פרטיות חדשות",
tooltipAutoscroll: "גלילה אוטומטית",
tooltipStatusmessage: "הצג הודעות מצב",
tooltipAdministration: "הנהלת חדר",
tooltipUsercount: "משתתפי חדר",
enterRoomPassword: 'חדר "%s" הינו מוגן סיסמה.',
enterRoomPasswordSubmit: "הצטרף לחדר",
passwordEnteredInvalid: 'סיסמה שגויה לחדר "%s".',
nicknameConflict: "שם משתמש כבר מצוי בשימוש. אנא בחר אחד אחר.",
errorMembersOnly: 'אין באפשרותך להצטרף לחדר "%s": הרשאות לקויות.',
errorMaxOccupantsReached: 'אין באפשרותך להצטרף לחדר "%s": יותר מדי משתתפים.',
errorAutojoinMissing: "לא נקבע פרמטר הצטרפות אוטומטית בתצורה. אנא הזן כזה כדי להמשיך.",
antiSpamMessage: "אנא אל תשלח ספאם. נחסמת למשך זמן קצר."
}
};
//# sourceMappingURL=candy.bundle.map
|
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional, Tuple, Union
import torch
from pytorch_lightning import utilities
from pytorch_lightning.metrics import utils
def _psnr_compute(
sum_squared_error: torch.Tensor,
n_obs: torch.Tensor,
data_range: torch.Tensor,
base: float = 10.0,
reduction: str = 'elementwise_mean',
) -> torch.Tensor:
psnr_base_e = 2 * torch.log(data_range) - torch.log(sum_squared_error / n_obs)
psnr = psnr_base_e * (10 / torch.log(torch.tensor(base)))
return utils.reduce(psnr, reduction=reduction)
def _psnr_update(preds: torch.Tensor,
target: torch.Tensor,
dim: Optional[Union[int, Tuple[int, ...]]] = None) -> Tuple[torch.Tensor, torch.Tensor]:
if dim is None:
sum_squared_error = torch.sum(torch.pow(preds - target, 2))
n_obs = torch.tensor(target.numel(), device=target.device)
return sum_squared_error, n_obs
sum_squared_error = torch.sum(torch.pow(preds - target, 2), dim=dim)
if isinstance(dim, int):
dim_list = [dim]
else:
dim_list = list(dim)
if not dim_list:
n_obs = torch.tensor(target.numel(), device=target.device)
else:
n_obs = torch.tensor(target.size(), device=target.device)[dim_list].prod()
n_obs = n_obs.expand_as(sum_squared_error)
return sum_squared_error, n_obs
def psnr(
preds: torch.Tensor,
target: torch.Tensor,
data_range: Optional[float] = None,
base: float = 10.0,
reduction: str = 'elementwise_mean',
dim: Optional[Union[int, Tuple[int, ...]]] = None,
) -> torch.Tensor:
"""
Computes the peak signal-to-noise ratio
Args:
preds: estimated signal
target: groun truth signal
data_range:
the range of the data. If None, it is determined from the data (max - min). ``data_range`` must be given
when ``dim`` is not None.
base: a base of a logarithm to use (default: 10)
reduction: a method to reduce metric score over labels.
- ``'elementwise_mean'``: takes the mean (default)
- ``'sum'``: takes the sum
- ``'none'``: no reduction will be applied
dim:
Dimensions to reduce PSNR scores over provided as either an integer or a list of integers. Default is
None meaning scores will be reduced across all dimensions.
Return:
Tensor with PSNR score
Example:
>>> from pytorch_lightning.metrics.functional import psnr
>>> pred = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
>>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]])
>>> psnr(pred, target)
tensor(2.5527)
"""
if dim is None and reduction != 'elementwise_mean':
utilities.rank_zero_warn(f'The `reduction={reduction}` will not have any effect when `dim` is None.')
if data_range is None:
if dim is not None:
# Maybe we could use `torch.amax(target, dim=dim) - torch.amin(target, dim=dim)` in PyTorch 1.7 to calculate
# `data_range` in the future.
raise ValueError("The `data_range` must be given when `dim` is not None.")
data_range = target.max() - target.min()
else:
data_range = torch.tensor(float(data_range))
sum_squared_error, n_obs = _psnr_update(preds, target, dim=dim)
return _psnr_compute(sum_squared_error, n_obs, data_range, base=base, reduction=reduction)
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["pages-custom-index~pages-index-index"],{"0051":function(t,e,n){"use strict";var i=n("956f"),a=n.n(i);a.a},"018f":function(t,e,n){var i=n("3842");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("407eb178",i,!0,{sourceMap:!1,shadowMode:!1})},"041e":function(t,e,n){"use strict";n.r(e);var i=n("f034"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},"05f9":function(t,e,n){var i=n("a915");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("40aec5d2",i,!0,{sourceMap:!1,shadowMode:!1})},"071e":function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-window",style:{background:t.itemStyle.background,padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px"}},[t.itemStyle.layout>-1?n("v-uni-view",{staticClass:"data-list",class:["avg-sm-"+t.itemStyle.layout]},t._l(t.dataList,(function(e,i){return n("v-uni-view",{key:i,staticClass:"data-item",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px"}},[n("v-uni-view",{staticClass:"item-image",on:{click:function(n){arguments[0]=n=t.$handleEvent(n),t.onLink(e.link)}}},[n("v-uni-image",{staticClass:"image",attrs:{mode:"widthFix",src:e.imgUrl}})],1)],1)})),1):n("v-uni-view",{staticClass:"display"},[n("v-uni-view",{staticClass:"display-left",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px"}},[n("v-uni-image",{staticClass:"image",attrs:{src:t.dataList[0].imgUrl},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onLink(t.dataList[0].link)}}})],1),n("v-uni-view",{staticClass:"display-right"},[t.dataList.length>=2?n("v-uni-view",{staticClass:"display-right1",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px"}},[n("v-uni-image",{staticClass:"image",attrs:{src:t.dataList[1].imgUrl},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onLink(t.dataList[1].link)}}})],1):t._e(),n("v-uni-view",{staticClass:"display-right2"},[t.dataList.length>=3?n("v-uni-view",{staticClass:"left",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px"}},[n("v-uni-image",{staticClass:"image",attrs:{src:t.dataList[2].imgUrl},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onLink(t.dataList[2].link)}}})],1):t._e(),t.dataList.length>=4?n("v-uni-view",{staticClass:"right",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px"}},[n("v-uni-image",{staticClass:"image",attrs:{src:t.dataList[3].imgUrl},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onLink(t.dataList[3].link)}}})],1):t._e()],1)],1)],1)],1)},r=[]},"0e86":function(t,e,n){"use strict";var i=n("4a96"),a=n.n(i);a.a},"11a9":function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-window .data-list[data-v-c3261462]::after{clear:both;content:" ";display:table}.diy-window .data-list .data-item[data-v-c3261462]{float:left;box-sizing:border-box}.diy-window .data-list .image[data-v-c3261462]{display:block;width:100%}\r\n/* 分列布局 */.diy-window .avg-sm-2 > .data-item[data-v-c3261462]{width:50%}.diy-window .avg-sm-3 > .data-item[data-v-c3261462]{width:33.33333333%}.diy-window .avg-sm-4 > .data-item[data-v-c3261462]{width:25%}.diy-window .avg-sm-5 > .data-item[data-v-c3261462]{width:20%}\r\n/* 橱窗样式 */.diy-window[data-v-c3261462]{box-sizing:border-box}.diy-window .display[data-v-c3261462]{height:0;width:100%;margin:0;padding-bottom:50%;position:relative;box-sizing:border-box}.diy-window .display .image[data-v-c3261462]{width:100%;height:100%}.diy-window .display .display-left[data-v-c3261462]{width:50%;height:100%;position:absolute;top:0;left:0;box-sizing:border-box}.diy-window .display .display-right[data-v-c3261462]{width:50%;height:100%;position:absolute;top:0;left:50%;box-sizing:border-box}.diy-window .display .display-right1[data-v-c3261462]{width:100%;height:50%;position:absolute;top:0;box-sizing:border-box;left:0}.diy-window .display .display-right2[data-v-c3261462]{width:100%;height:50%;position:absolute;top:50%;left:0;box-sizing:border-box}.diy-window .display .display-right2 .left[data-v-c3261462]{width:50%;height:100%;position:absolute;top:0;left:0;box-sizing:border-box}.diy-window .display .display-right2 .right[data-v-c3261462]{width:50%;height:100%;position:absolute;top:0;left:50%;box-sizing:border-box}',""]),t.exports=e},1212:function(t,e,n){"use strict";n.r(e);var i=n("14e1"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},"12dd":function(t,e,n){"use strict";var i=n("27fb"),a=n.n(i);a.a},"14e1":function(t,e,n){"use strict";n("a9e3"),n("d3b7"),n("ac1f"),n("3ca3"),n("ddb0"),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{list:{type:Array,default:function(){return[]}},type:{type:String,default:"warning"},volumeIcon:{type:Boolean,default:!0},moreIcon:{type:Boolean,default:!1},closeIcon:{type:Boolean,default:!1},autoplay:{type:Boolean,default:!0},color:{type:String,default:""},bgColor:{type:String,default:""},show:{type:Boolean,default:!0},fontSize:{type:[Number,String],default:26},volumeSize:{type:[Number,String],default:34},speed:{type:[Number,String],default:160},playState:{type:String,default:"play"},padding:{type:[Number,String],default:"18rpx 24rpx"}},data:function(){return{textWidth:0,boxWidth:0,animationDuration:"10s",animationPlayState:"paused",showText:""}},watch:{list:{immediate:!0,handler:function(t){var e=this;this.showText=t.join(","),this.$nextTick((function(){e.initSize()}))}},playState:function(t){this.animationPlayState="play"==t?"running":"paused"},speed:function(t){this.initSize()}},computed:{computeColor:function(){return this.color?this.color:"none"==this.type?"#606266":this.type},textStyle:function(){var t={};return this.color?t.color=this.color:"none"==this.type&&(t.color="#606266"),t.fontSize=this.fontSize+"rpx",t},computeBgColor:function(){return this.bgColor?this.bgColor:"none"==this.type?"transparent":void 0}},mounted:function(){var t=this;this.$nextTick((function(){t.initSize()}))},methods:{initSize:function(){var t=this,e=[],n=new Promise((function(e,n){uni.createSelectorQuery().in(t).select("#u-notice-content").boundingClientRect().exec((function(n){t.textWidth=n[0].width,e()}))}));e.push(n),Promise.all(e).then((function(){t.animationDuration="".concat(t.textWidth/uni.upx2px(t.speed),"s"),t.animationPlayState="paused",setTimeout((function(){"play"==t.playState&&t.autoplay&&(t.animationPlayState="running")}),10)}))},click:function(t){this.$emit("click")},close:function(){this.$emit("close")},getMore:function(){this.$emit("getMore")}}};e.default=i},"15ae":function(t,e,n){var i=n("a442");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("be036eb6",i,!0,{sourceMap:!1,shadowMode:!1})},"1bd2":function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-imageSingle .item-image .image[data-v-1eb36b0c]{display:block;width:100%}',""]),t.exports=e},"1f0a":function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-search"},[n("v-uni-view",{staticClass:"inner",class:t.itemStyle.searchStyle,on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onTargetSearch.apply(void 0,arguments)}}},[n("v-uni-view",{staticClass:"search-input",style:{textAlign:t.itemStyle.textAlign}},[n("v-uni-text",{staticClass:"search-icon iconfont icon-search"}),n("v-uni-text",[t._v(t._s(t.params.placeholder))])],1)],1)],1)},r=[]},"1fc3":function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var a=i(n("2d22")),r={name:"NavBar",props:{itemIndex:String,itemStyle:Object,params:Object,dataList:Array},mixins:[a.default],methods:{}};e.default=r},2039:function(t,e,n){"use strict";n.r(e);var i=n("cf19"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},"246e":function(t,e,n){var i=n("5867");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("1b541dac",i,!0,{sourceMap:!1,shadowMode:!1})},"27fb":function(t,e,n){var i=n("1bd2");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("b3de135e",i,!0,{sourceMap:!1,shadowMode:!1})},"2a58":function(t,e,n){var i=n("bcfc");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("d0a8f872",i,!0,{sourceMap:!1,shadowMode:!1})},"2abd":function(t,e,n){"use strict";n.r(e);var i=n("75f4"),a=n("1212");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("7c45");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"4bc00da4",null,!1,i["a"],o);e["default"]=c.exports},"2d22":function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;i(n("7d61"));var a={data:function(){return{}},methods:{onLink:function(t){return!!t&&("PAGE"===t.type&&this.$navTo(t.param.path,t.param.query),!0)}}};e.default=a},"2dcb":function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-richText[data-v-acb467e4]{font-size:%?28?%}',""]),t.exports=e},"35be":function(t,e,n){"use strict";n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var i={uNoticeBar:n("e2eb").default},a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-notice",style:{paddingTop:t.itemStyle.paddingTop+"px",paddingBottom:t.itemStyle.paddingTop+"px"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onLink(t.params.link)}}},[n("u-notice-bar",{attrs:{padding:"10rpx 24rpx","volume-icon":t.params.showIcon,autoplay:t.params.scrollable,"bg-color":t.itemStyle.background,color:t.itemStyle.textColor,list:[t.params.text]}})],1)},r=[]},3842:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-navBar .data-list[data-v-75bc6be2]::after{clear:both;content:" ";display:table}.item-nav[data-v-75bc6be2]{float:left;margin:10px 0;text-align:center}.item-nav .item-text[data-v-75bc6be2]{font-size:%?26?%}.item-nav .item-image[data-v-75bc6be2]{margin-bottom:4px;font-size:0}.item-nav .item-image .image[data-v-75bc6be2]{width:%?88?%;height:%?88?%}\r\n/* 分列布局 */.diy-navBar .avg-sm-3 > .item-nav[data-v-75bc6be2]{width:33.33333333%}.diy-navBar .avg-sm-4 > .item-nav[data-v-75bc6be2]{width:25%}.diy-navBar .avg-sm-5 > .item-nav[data-v-75bc6be2]{width:20%}',""]),t.exports=e},"3fff":function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-blank",style:{height:t.itemStyle.height+"px",background:t.itemStyle.background}})},r=[]},4306:function(t,e,n){"use strict";n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var i={uIcon:n("f9d0").default},a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"u-notice-bar",class:[t.type?"u-type-"+t.type+"-light-bg":""],style:{background:t.computeBgColor,padding:t.padding}},[n("v-uni-view",{staticClass:"u-icon-wrap"},[t.volumeIcon?n("u-icon",{staticClass:"u-left-icon",attrs:{name:"volume-fill",size:t.volumeSize,color:t.computeColor}}):t._e()],1),n("v-uni-swiper",{staticClass:"u-swiper",attrs:{"disable-touch":t.disableTouch,autoplay:t.autoplay&&"play"==t.playState,vertical:t.vertical,circular:!0,interval:t.duration},on:{change:function(e){arguments[0]=e=t.$handleEvent(e),t.change.apply(void 0,arguments)}}},t._l(t.list,(function(e,i){return n("v-uni-swiper-item",{key:i,staticClass:"u-swiper-item"},[n("v-uni-view",{staticClass:"u-news-item u-line-1",class:["u-type-"+t.type],style:[t.textStyle],on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.click(i)}}},[t._v(t._s(e))])],1)})),1),n("v-uni-view",{staticClass:"u-icon-wrap"},[t.moreIcon?n("u-icon",{staticClass:"u-right-icon",attrs:{name:"arrow-right",size:26,color:t.computeColor},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.getMore.apply(void 0,arguments)}}}):t._e(),t.closeIcon?n("u-icon",{staticClass:"u-right-icon",attrs:{name:"close",size:24,color:t.computeColor},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.close.apply(void 0,arguments)}}}):t._e()],1)],1)},r=[]},"49b7":function(t,e,n){"use strict";var i=n("8efc"),a=n.n(i);a.a},"4a96":function(t,e,n){var i=n("6074");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("98f1e43c",i,!0,{sourceMap:!1,shadowMode:!1})},"4ef3":function(t,e,n){"use strict";var i=n("246e"),a=n.n(i);a.a},"52df":function(t,e,n){"use strict";var i=n("a098"),a=n.n(i);a.a},"537f":function(t,e,n){"use strict";var i=n("80e8"),a=n.n(i);a.a},5430:function(t,e,n){var i=n("ee84");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("04a21c43",i,!0,{sourceMap:!1,shadowMode:!1})},5867:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.u-notice-bar[data-v-18d2347f]{width:100%;display:flex;flex-direction:row;align-items:center;justify-content:center;flex-wrap:nowrap;padding:%?18?% %?24?%;overflow:hidden}.u-swiper[data-v-18d2347f]{font-size:%?26?%;height:%?32?%;display:flex;flex-direction:row;align-items:center;flex:1;margin-left:%?12?%}.u-swiper-item[data-v-18d2347f]{display:flex;flex-direction:row;align-items:center;overflow:hidden}.u-news-item[data-v-18d2347f]{overflow:hidden}.u-right-icon[data-v-18d2347f]{margin-left:%?12?%;display:inline-flex;align-items:center}.u-left-icon[data-v-18d2347f]{display:inline-flex;align-items:center}',""]),t.exports=e},"5f89":function(t,e,n){"use strict";n("a9e3"),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={name:"u-notice-bar",props:{list:{type:Array,default:function(){return[]}},type:{type:String,default:"warning"},volumeIcon:{type:Boolean,default:!0},volumeSize:{type:[Number,String],default:34},moreIcon:{type:Boolean,default:!1},closeIcon:{type:Boolean,default:!1},autoplay:{type:Boolean,default:!0},color:{type:String,default:""},bgColor:{type:String,default:""},mode:{type:String,default:"horizontal"},show:{type:Boolean,default:!0},fontSize:{type:[Number,String],default:28},duration:{type:[Number,String],default:2e3},speed:{type:[Number,String],default:160},isCircular:{type:Boolean,default:!0},playState:{type:String,default:"play"},disableTouch:{type:Boolean,default:!0},borderRadius:{type:[Number,String],default:0},padding:{type:[Number,String],default:"18rpx 24rpx"},noListHidden:{type:Boolean,default:!0}},computed:{isShow:function(){return 0!=this.show&&(1!=this.noListHidden||0!=this.list.length)}},methods:{click:function(t){this.$emit("click",t)},close:function(){this.$emit("close")},getMore:function(){this.$emit("getMore")},end:function(){this.$emit("end")}}};e.default=i},6074:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-search[data-v-fffb5964]{background:#f1f1f2;padding:%?20?% %?20?%;font-size:%?26?%}.inner[data-v-fffb5964]{height:%?60?%;background:#fff;overflow:hidden}.inner.radius[data-v-fffb5964]{border-radius:%?10?%}.inner.round[data-v-fffb5964]{border-radius:%?60?%}.search-input[data-v-fffb5964]{height:%?60?%;line-height:%?60?%;color:#999;padding:0 %?20?%}.search-input .search-icon[data-v-fffb5964]{margin-right:%?8?%}',""]),t.exports=e},6251:function(t,e,n){"use strict";n.r(e);var i=n("ccc2"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},"6f44":function(t,e,n){"use strict";n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var i={uRowNotice:n("2abd").default,uColumnNotice:n("c434").default},a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.isShow?n("v-uni-view",{staticClass:"u-notice-bar-wrap",style:{borderRadius:t.borderRadius+"rpx"}},["horizontal"==t.mode&&t.isCircular?[n("u-row-notice",{attrs:{type:t.type,color:t.color,bgColor:t.bgColor,list:t.list,volumeIcon:t.volumeIcon,moreIcon:t.moreIcon,volumeSize:t.volumeSize,closeIcon:t.closeIcon,mode:t.mode,fontSize:t.fontSize,speed:t.speed,playState:t.playState,padding:t.padding},on:{getMore:function(e){arguments[0]=e=t.$handleEvent(e),t.getMore.apply(void 0,arguments)},close:function(e){arguments[0]=e=t.$handleEvent(e),t.close.apply(void 0,arguments)},click:function(e){arguments[0]=e=t.$handleEvent(e),t.click.apply(void 0,arguments)}}})]:t._e(),"vertical"==t.mode||"horizontal"==t.mode&&!t.isCircular?[n("u-column-notice",{attrs:{type:t.type,color:t.color,bgColor:t.bgColor,list:t.list,volumeIcon:t.volumeIcon,moreIcon:t.moreIcon,closeIcon:t.closeIcon,mode:t.mode,volumeSize:t.volumeSize,"disable-touch":t.disableTouch,fontSize:t.fontSize,duration:t.duration,playState:t.playState,padding:t.padding},on:{getMore:function(e){arguments[0]=e=t.$handleEvent(e),t.getMore.apply(void 0,arguments)},close:function(e){arguments[0]=e=t.$handleEvent(e),t.close.apply(void 0,arguments)},click:function(e){arguments[0]=e=t.$handleEvent(e),t.click.apply(void 0,arguments)},end:function(e){arguments[0]=e=t.$handleEvent(e),t.end.apply(void 0,arguments)}}})]:t._e()],2):t._e()},r=[]},"70c7":function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-imageSingle",style:{paddingBottom:t.itemStyle.paddingTop+"px",background:t.itemStyle.background}},t._l(t.dataList,(function(e,i){return n("v-uni-view",{key:i,staticClass:"item-image",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px 0"}},[n("v-uni-view",{staticClass:"nav-to",on:{click:function(n){arguments[0]=n=t.$handleEvent(n),t.onLink(e.link)}}},[n("v-uni-image",{staticClass:"image",attrs:{src:e.imgUrl,mode:"widthFix"}})],1)],1)})),1)},r=[]},7261:function(t,e,n){"use strict";n.r(e);var i=n("071e"),a=n("8a6a");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("ebd2");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"c3261462",null,!1,i["a"],o);e["default"]=c.exports},"75e4":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{itemIndex:String,itemStyle:Object,params:Object},methods:{onTargetSearch:function(){this.$navTo("pages/search/index")}}};e.default=i},"75f4":function(t,e,n){"use strict";n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var i={uIcon:n("f9d0").default},a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.show?n("v-uni-view",{staticClass:"u-notice-bar",class:[t.type?"u-type-"+t.type+"-light-bg":""],style:{background:t.computeBgColor,padding:t.padding}},[n("v-uni-view",{staticClass:"u-direction-row"},[n("v-uni-view",{staticClass:"u-icon-wrap"},[t.volumeIcon?n("u-icon",{staticClass:"u-left-icon",attrs:{name:"volume-fill",size:t.volumeSize,color:t.computeColor}}):t._e()],1),n("v-uni-view",{staticClass:"u-notice-box",attrs:{id:"u-notice-box"}},[n("v-uni-view",{staticClass:"u-notice-content",style:{animationDuration:t.animationDuration,animationPlayState:t.animationPlayState},attrs:{id:"u-notice-content"}},[n("v-uni-text",{staticClass:"u-notice-text",class:["u-type-"+t.type],style:[t.textStyle],on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.click.apply(void 0,arguments)}}},[t._v(t._s(t.showText))])],1)],1),n("v-uni-view",{staticClass:"u-icon-wrap"},[t.moreIcon?n("u-icon",{staticClass:"u-right-icon",attrs:{name:"arrow-right",size:26,color:t.computeColor},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.getMore.apply(void 0,arguments)}}}):t._e(),t.closeIcon?n("u-icon",{staticClass:"u-right-icon",attrs:{name:"close",size:24,color:t.computeColor},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.close.apply(void 0,arguments)}}}):t._e()],1)],1)],1):t._e()},r=[]},"7c45":function(t,e,n){"use strict";var i=n("2a58"),a=n.n(i);a.a},"7d2e":function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-goods",style:{background:t.itemStyle.background}},[n("v-uni-view",{staticClass:"goods-list",class:["display__"+t.itemStyle.display,"column__"+t.itemStyle.column]},[n("v-uni-scroll-view",{attrs:{"scroll-x":"slide"===t.itemStyle.display}},t._l(t.dataList,(function(e,i){return n("v-uni-view",{key:i,staticClass:"goods-item",on:{click:function(n){arguments[0]=n=t.$handleEvent(n),t.onTargetGoods(e.goods_id)}}},[1===t.itemStyle.column?[n("v-uni-view",{staticClass:"dis-flex"},[n("v-uni-view",{staticClass:"goods-item_left"},[n("v-uni-image",{staticClass:"image",attrs:{src:e.goods_image}})],1),n("v-uni-view",{staticClass:"goods-item_right"},[t.itemStyle.show.includes("goodsName")?n("v-uni-view",{staticClass:"goods-name"},[n("v-uni-text",{staticClass:"twoline-hide"},[t._v(t._s(e.goods_name))])],1):t._e(),n("v-uni-view",{staticClass:"goods-item_desc"},[t.itemStyle.show.includes("sellingPoint")?n("v-uni-view",{staticClass:"desc-selling_point dis-flex"},[n("v-uni-text",{staticClass:"oneline-hide"},[t._v(t._s(e.selling_point))])],1):t._e(),t.itemStyle.show.includes("goodsSales")?n("v-uni-view",{staticClass:"desc-goods_sales dis-flex"},[n("v-uni-text",[t._v("已售"+t._s(e.goods_sales)+"件")])],1):t._e(),n("v-uni-view",{staticClass:"desc_footer"},[t.itemStyle.show.includes("goodsPrice")?n("v-uni-text",{staticClass:"price_x"},[t._v("¥"+t._s(e.goods_price_min))]):t._e(),t.itemStyle.show.includes("linePrice")&&e.line_price_min>0?n("v-uni-text",{staticClass:"price_y col-9"},[t._v("¥"+t._s(e.line_price_min))]):t._e()],1)],1)],1)],1)]:[n("v-uni-view",{staticClass:"goods-image"},[n("v-uni-image",{staticClass:"image",attrs:{mode:"aspectFill",src:e.goods_image}})],1),n("v-uni-view",{staticClass:"detail"},[t.itemStyle.show.includes("goodsName")?n("v-uni-view",{staticClass:"goods-name"},[n("v-uni-text",{staticClass:"twoline-hide"},[t._v(t._s(e.goods_name))])],1):t._e(),n("v-uni-view",{staticClass:"detail-price oneline-hide"},[t.itemStyle.show.includes("goodsPrice")?n("v-uni-text",{staticClass:"goods-price f-30 col-m"},[t._v("¥"+t._s(e.goods_price_min))]):t._e(),t.itemStyle.show.includes("linePrice")&&e.line_price_min>0?n("v-uni-text",{staticClass:"line-price col-9 f-24"},[t._v("¥"+t._s(e.line_price_min))]):t._e()],1)],1)]],2)})),1)],1)],1)},r=[]},"80e8":function(t,e,n){var i=n("efc5");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("42014b42",i,!0,{sourceMap:!1,shadowMode:!1})},8825:function(t,e,n){"use strict";n.r(e);var i=n("cd20"),a=n("041e");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("b2ac");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"4afd20ca",null,!1,i["a"],o);e["default"]=c.exports},"8a6a":function(t,e,n){"use strict";n.r(e);var i=n("cd75"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},"8c21":function(t,e,n){"use strict";n.r(e);var i=n("d21b"),a=n("a83c");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("8f12");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"a7d5e724",null,!1,i["a"],o);e["default"]=c.exports},"8dc1":function(t,e,n){"use strict";n.r(e);var i=n("a4da"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},"8efc":function(t,e,n){var i=n("c326");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("6c3d109d",i,!0,{sourceMap:!1,shadowMode:!1})},"8f12":function(t,e,n){"use strict";var i=n("5430"),a=n.n(i);a.a},"8f65":function(t,e,n){"use strict";n.r(e);var i=n("f89f"),a=n("f07c");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("e6ce");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"75bc6be2",null,!1,i["a"],o);e["default"]=c.exports},"91bf":function(t,e,n){"use strict";var i=n("05f9"),a=n.n(i);a.a},9230:function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-guide",style:{padding:t.itemStyle.paddingTop+"px 0",background:t.itemStyle.background}},[n("v-uni-view",{staticClass:"line",style:{borderTop:t.itemStyle.lineHeight+"px "+t.itemStyle.lineStyle+" "+t.itemStyle.lineColor}})],1)},r=[]},9316:function(t,e,n){"use strict";n.r(e);var i=n("a3e4"),a=n("a200");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("0051");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"acb467e4",null,!1,i["a"],o);e["default"]=c.exports},"956f":function(t,e,n){var i=n("2dcb");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("3f80e629",i,!0,{sourceMap:!1,shadowMode:!1})},"9bbe":function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return"chat"!==t.params.type||t.isMpWeiXin?n("v-uni-view",{staticClass:"diy-service",style:{"--right":t.right+"px","--bottom":t.bottom+"px"}},["phone"===t.params.type?[n("v-uni-view",{staticClass:"service-icon",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onMakePhoneCall.apply(void 0,arguments)}}},[n("v-uni-image",{staticClass:"image",attrs:{src:t.params.image}})],1)]:"chat"==t.params.type?[n("v-uni-button",{staticClass:"btn-normal",attrs:{"open-type":"contact"}},[n("v-uni-view",{staticClass:"service-icon"},[n("v-uni-image",{staticClass:"image",attrs:{src:t.params.image}})],1)],1)]:t._e()],2):t._e()},r=[]},a093:function(t,e,n){"use strict";n.r(e);var i=n("70c7"),a=n("bf40");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("12dd");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"1eb36b0c",null,!1,i["a"],o);e["default"]=c.exports},a098:function(t,e,n){var i=n("f95b");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("0ec06e44",i,!0,{sourceMap:!1,shadowMode:!1})},a200:function(t,e,n){"use strict";n.r(e);var i=n("d2b9"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},a3e4:function(t,e,n){"use strict";n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var i={mpHtml:n("b3c7").default},a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-richText",style:{padding:t.itemStyle.paddingTop+"px "+t.itemStyle.paddingLeft+"px",background:t.itemStyle.background}},[n("mp-html",{attrs:{content:t.params.content}})],1)},r=[]},a442:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.u-notice-bar-wrap[data-v-386306c2]{overflow:hidden}.u-notice-bar[data-v-386306c2]{padding:%?18?% %?24?%;overflow:hidden}.u-direction-row[data-v-386306c2]{display:flex;flex-direction:row;align-items:center;justify-content:space-between}.u-left-icon[data-v-386306c2]{display:flex;flex-direction:row;align-items:center}.u-notice-box[data-v-386306c2]{flex:1;display:flex;flex-direction:row;overflow:hidden;margin-left:%?12?%}.u-right-icon[data-v-386306c2]{margin-left:%?12?%;display:flex;flex-direction:row;align-items:center}.u-notice-content[data-v-386306c2]{line-height:1;white-space:nowrap;font-size:%?26?%;-webkit-animation:u-loop-animation-data-v-386306c2 10s linear infinite both;animation:u-loop-animation-data-v-386306c2 10s linear infinite both;text-align:right;padding-left:100%}@-webkit-keyframes u-loop-animation-data-v-386306c2{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}100%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}@keyframes u-loop-animation-data-v-386306c2{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}100%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}',""]),t.exports=e},a4da:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={name:"Videos",props:{itemIndex:String,itemStyle:Object,params:Object},methods:{}};e.default=i},a5eb:function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var a=i(n("2d22")),r={props:{itemStyle:Object,params:Object},mixins:[a.default],methods:{}};e.default=r},a83c:function(t,e,n){"use strict";n.r(e);var i=n("b94c"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},a876:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{itemStyle:Object},methods:{}};e.default=i},a915:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-video .video[data-v-a0f6c1b8]{width:100%;display:block}',""]),t.exports=e},ab96:function(t,e,n){"use strict";n.r(e);var i=n("f1ae"),a=n("8dc1");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("91bf");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"a0f6c1b8",null,!1,i["a"],o);e["default"]=c.exports},af56:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{itemStyle:Object},methods:{}};e.default=i},b2ac:function(t,e,n){"use strict";var i=n("f9eb"),a=n.n(i);a.a},b3ac:function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.detail=o;var a=i(n("c05a")),r={detail:"page/detail"};function o(t){return a.default.get(r.detail,{pageId:t})}},b5e7:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i=n("7d61"),a={props:{itemStyle:Object,params:Object},data:function(){return{isMpWeiXin:!1,isShow:!0}},computed:{right:function(){return(0,i.rpx2px)(2*this.itemStyle.right)},bottom:function(){return(0,i.rpx2px)(2*this.itemStyle.bottom)}},created:function(){},methods:{onMakePhoneCall:function(t){uni.makePhoneCall({phoneNumber:this.params.tel})}}};e.default=a},b72b:function(t,e,n){"use strict";n.r(e);var i=n("75e4"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},b94c:function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var a=i(n("2d22")),r={name:"Banner",props:{itemIndex:String,itemStyle:Object,params:Object,dataList:Array},mixins:[a.default],data:function(){return{windowWidth:750,indicatorDots:!1,autoplay:!0,duration:800,imgHeights:[],imgCurrent:0}},created:function(){var t=this;uni.getSystemInfo({success:function(e){var n=e.windowWidth;t.windowWidth=n>750?750:n}})},methods:{_imagesHeight:function(t){var e=t.detail,n=this,i=e.width,a=e.height,r=i/a,o=n.windowWidth/r;n.imgHeights.push(o)},_bindChange:function(t){this.imgCurrent=t.detail.current}}};e.default=r},ba79:function(t,e,n){"use strict";n.r(e);var i=n("1f0a"),a=n("b72b");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("0e86");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"fffb5964",null,!1,i["a"],o);e["default"]=c.exports},bcfc:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.u-notice-bar[data-v-4bc00da4]{padding:%?18?% %?24?%;overflow:hidden}.u-direction-row[data-v-4bc00da4]{display:flex;flex-direction:row;align-items:center;justify-content:space-between}.u-left-icon[data-v-4bc00da4]{display:inline-flex;align-items:center}.u-notice-box[data-v-4bc00da4]{flex:1;display:flex;flex-direction:row;overflow:hidden;margin-left:%?12?%}.u-right-icon[data-v-4bc00da4]{margin-left:%?12?%;display:inline-flex;align-items:center}.u-notice-content[data-v-4bc00da4]{-webkit-animation:u-loop-animation-data-v-4bc00da4 10s linear infinite both;animation:u-loop-animation-data-v-4bc00da4 10s linear infinite both;text-align:right;padding-left:100%;display:flex;flex-direction:row;flex-wrap:nowrap}.u-notice-text[data-v-4bc00da4]{font-size:%?26?%;word-break:keep-all;white-space:nowrap}@-webkit-keyframes u-loop-animation-data-v-4bc00da4{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}100%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}@keyframes u-loop-animation-data-v-4bc00da4{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}100%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}',""]),t.exports=e},bf40:function(t,e,n){"use strict";n.r(e);var i=n("f577"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},c183:function(t,e,n){var i=n("d14e");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("e818e7d6",i,!0,{sourceMap:!1,shadowMode:!1})},c326:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-article[data-v-d9182fbe]{background:#f7f7f7}.diy-article .article-item[data-v-d9182fbe]{margin-bottom:%?20?%;padding:%?30?%;background:#fff}.diy-article .article-item[data-v-d9182fbe]:last-child{margin-bottom:0}.diy-article .article-item .article-item__title[data-v-d9182fbe]{max-height:%?74?%;font-size:%?28?%;line-height:%?38?%;color:#333}.diy-article .article-item .article-item__image .image[data-v-d9182fbe]{display:block}\r\n/* 小图模式 */.show-type__10[data-v-d9182fbe]{display:flex}.show-type__10 .article-item__left[data-v-d9182fbe]{padding-right:%?20?%}.show-type__10 .article-item__image .image[data-v-d9182fbe]{width:%?240?%}\r\n/* 大图模式 */.show-type__20 .article-item__image .image[data-v-d9182fbe]{width:100%}',""]),t.exports=e},c434:function(t,e,n){"use strict";n.r(e);var i=n("4306"),a=n("6251");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("4ef3");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"18d2347f",null,!1,i["a"],o);e["default"]=c.exports},c4e9:function(t,e,n){"use strict";n.r(e);var i=n("9bbe"),a=n("d9ee");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("52df");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"e52309a8",null,!1,i["a"],o);e["default"]=c.exports},ca7e:function(t,e,n){"use strict";n.r(e);var i=n("9230"),a=n("e372");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("eb50");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"69980692",null,!1,i["a"],o);e["default"]=c.exports},ccc2:function(t,e,n){"use strict";n("a9e3"),Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{list:{type:Array,default:function(){return[]}},type:{type:String,default:"warning"},volumeIcon:{type:Boolean,default:!0},moreIcon:{type:Boolean,default:!1},closeIcon:{type:Boolean,default:!1},autoplay:{type:Boolean,default:!0},color:{type:String,default:""},bgColor:{type:String,default:""},direction:{type:String,default:"row"},show:{type:Boolean,default:!0},fontSize:{type:[Number,String],default:26},duration:{type:[Number,String],default:2e3},volumeSize:{type:[Number,String],default:34},speed:{type:Number,default:160},isCircular:{type:Boolean,default:!0},mode:{type:String,default:"horizontal"},playState:{type:String,default:"play"},disableTouch:{type:Boolean,default:!0},padding:{type:[Number,String],default:"18rpx 24rpx"}},computed:{computeColor:function(){return this.color?this.color:"none"==this.type?"#606266":this.type},textStyle:function(){var t={};return this.color?t.color=this.color:"none"==this.type&&(t.color="#606266"),t.fontSize=this.fontSize+"rpx",t},vertical:function(){return"horizontal"!=this.mode},computeBgColor:function(){return this.bgColor?this.bgColor:"none"==this.type?"transparent":void 0}},data:function(){return{}},methods:{click:function(t){this.$emit("click",t)},close:function(){this.$emit("close")},getMore:function(){this.$emit("getMore")},change:function(t){var e=t.detail.current;e==this.list.length-1&&this.$emit("end")}}};e.default=i},cd01:function(t,e,n){"use strict";var i=n("15ae"),a=n.n(i);a.a},cd20:function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"page-items"},[t._l(t.items,(function(e,i){return["search"===e.type?[n("Search",{attrs:{itemStyle:e.style,params:e.params}})]:t._e(),"image"===e.type?[n("Images",{attrs:{itemStyle:e.style,params:e.params,dataList:e.data}})]:t._e(),"banner"===e.type?[n("Banner",{attrs:{itemStyle:e.style,params:e.params,dataList:e.data}})]:t._e(),"window"===e.type?[n("Window",{attrs:{itemStyle:e.style,params:e.params,dataList:e.data}})]:t._e(),"video"===e.type?[n("Videos",{attrs:{itemStyle:e.style,params:e.params}})]:t._e(),"article"===e.type?[n("Article",{attrs:{params:e.params,dataList:e.data}})]:t._e(),"notice"===e.type?[n("Notice",{attrs:{itemStyle:e.style,params:e.params}})]:t._e(),"navBar"===e.type?[n("NavBar",{attrs:{itemStyle:e.style,params:e.params,dataList:e.data}})]:t._e(),"goods"===e.type?[n("Goods",{attrs:{itemStyle:e.style,params:e.params,dataList:e.data}})]:t._e(),"service"===e.type?[n("Service",{attrs:{itemStyle:e.style,params:e.params}})]:t._e(),"blank"===e.type?[n("Blank",{attrs:{itemStyle:e.style}})]:t._e(),"guide"===e.type?[n("Guide",{attrs:{itemStyle:e.style}})]:t._e(),"richText"===e.type?[n("RichText",{attrs:{itemStyle:e.style,params:e.params}})]:t._e()]}))],2)},r=[]},cd75:function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var a=i(n("2d22")),r={name:"Window",props:{itemIndex:String,itemStyle:Object,params:Object,dataList:Array},mixins:[a.default],methods:{}};e.default=r},cf19:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={name:"Goods",props:{itemIndex:String,itemStyle:Object,params:Object,dataList:Array},methods:{onTargetGoods:function(t){this.$navTo("pages/goods/detail",{goodsId:t})}}};e.default=i},d14e:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-guide .line[data-v-69980692]{width:100%}',""]),t.exports=e},d21b:function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-banner",style:{height:t.imgHeights[t.imgCurrent]+"px"}},[n("v-uni-swiper",{staticClass:"swiper-box",attrs:{autoplay:t.autoplay,duration:t.duration,circular:!0,interval:1e3*t.itemStyle.interval},on:{change:function(e){arguments[0]=e=t.$handleEvent(e),t._bindChange.apply(void 0,arguments)}}},t._l(t.dataList,(function(e,i){return n("v-uni-swiper-item",{key:i},[n("v-uni-image",{staticClass:"slide-image",attrs:{mode:"widthFix",src:e.imgUrl},on:{click:function(n){arguments[0]=n=t.$handleEvent(n),t.onLink(e.link)},load:function(e){arguments[0]=e=t.$handleEvent(e),t._imagesHeight.apply(void 0,arguments)}}})],1)})),1),n("v-uni-view",{staticClass:"indicator-dots",class:t.itemStyle.btnShape},t._l(t.dataList,(function(e,i){return n("v-uni-view",{key:i,staticClass:"dots-item",class:{active:t.imgCurrent==i},style:{backgroundColor:t.itemStyle.btnColor}})})),1)],1)},r=[]},d2b9:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{itemStyle:Object,params:Object},methods:{}};e.default=i},d9ee:function(t,e,n){"use strict";n.r(e);var i=n("b5e7"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},db3b:function(t,e,n){"use strict";n.r(e);var i=n("ea42"),a=n("ed26");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("49b7");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"d9182fbe",null,!1,i["a"],o);e["default"]=c.exports},e21f:function(t,e,n){"use strict";n.r(e);var i=n("a5eb"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},e2eb:function(t,e,n){"use strict";n.r(e);var i=n("6f44"),a=n("e48b");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("cd01");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"386306c2",null,!1,i["a"],o);e["default"]=c.exports},e372:function(t,e,n){"use strict";n.r(e);var i=n("a876"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},e48b:function(t,e,n){"use strict";n.r(e);var i=n("5f89"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},e6ce:function(t,e,n){"use strict";var i=n("018f"),a=n.n(i);a.a},e7a8:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={name:"Article",props:{itemIndex:String,params:Object,dataList:Array},methods:{onTargetDetail:function(t){uni.navigateTo({url:"/pages/article/detail?articleId="+t})}}};e.default=i},ea42:function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-article"},t._l(t.dataList,(function(e,i){return n("v-uni-view",{key:i,staticClass:"article-item",class:["show-type__"+e.show_type],on:{click:function(n){arguments[0]=n=t.$handleEvent(n),t.onTargetDetail(e.article_id)}}},[10==e.show_type?[n("v-uni-view",{staticClass:"article-item__left flex-box"},[n("v-uni-view",{staticClass:"article-item__title"},[n("v-uni-text",{staticClass:"twoline-hide"},[t._v(t._s(e.title))])],1),n("v-uni-view",{staticClass:"article-item__footer m-top10"},[n("v-uni-text",{staticClass:"article-views f-24 col-8"},[t._v(t._s(e.show_views)+"次浏览")])],1)],1),n("v-uni-view",{staticClass:"article-item__image"},[n("v-uni-image",{staticClass:"image",attrs:{mode:"widthFix",src:e.image_url}})],1)]:t._e(),20==e.show_type?[n("v-uni-view",{staticClass:"article-item__title"},[n("v-uni-text",{staticClass:"twoline-hide"},[t._v(t._s(e.title))])],1),n("v-uni-view",{staticClass:"article-item__image m-top20"},[n("v-uni-image",{staticClass:"image",attrs:{mode:"widthFix",src:e.image_url}})],1),n("v-uni-view",{staticClass:"article-item__footer m-top10"},[n("v-uni-text",{staticClass:"article-views f-24 col-8"},[t._v(t._s(e.show_views)+"次浏览")])],1)]:t._e()],2)})),1)},r=[]},eb3a:function(t,e,n){"use strict";n.r(e);var i=n("af56"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},eb50:function(t,e,n){"use strict";var i=n("c183"),a=n.n(i);a.a},ebd2:function(t,e,n){"use strict";var i=n("fa2c"),a=n.n(i);a.a},ed26:function(t,e,n){"use strict";n.r(e);var i=n("e7a8"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},ee84:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-banner[data-v-a7d5e724]{position:relative\r\n /* 指示点 */}.diy-banner .swiper-box[data-v-a7d5e724]{height:100%}.diy-banner .swiper-box .slide-image[data-v-a7d5e724]{width:100%;height:100%;margin:0 auto;display:block}.diy-banner .indicator-dots[data-v-a7d5e724]{width:100%;height:%?28?%;padding:0 %?20?%;position:absolute;left:0;right:0;bottom:%?20?%;opacity:.8;display:flex;justify-content:center}.diy-banner .indicator-dots .dots-item[data-v-a7d5e724]{width:%?16?%;height:%?16?%;margin-right:%?8?%;background-color:#fff}.diy-banner .indicator-dots .dots-item[data-v-a7d5e724]:last-child{margin-right:0}.diy-banner .indicator-dots .dots-item.active[data-v-a7d5e724]{background-color:#313131!important}.diy-banner .indicator-dots.round .dots-item[data-v-a7d5e724]{width:%?16?%;height:%?16?%;border-radius:%?20?%}.diy-banner .indicator-dots.square .dots-item[data-v-a7d5e724]{width:%?16?%;height:%?16?%}.diy-banner .indicator-dots.rectangle .dots-item[data-v-a7d5e724]{width:%?22?%;height:%?14?%}',""]),t.exports=e},efc5:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-goods .goods-list[data-v-22fcf626]{padding:%?4?%;box-sizing:border-box}.diy-goods .goods-list .goods-item[data-v-22fcf626]{box-sizing:border-box;padding:%?6?%}.diy-goods .goods-list .goods-item .goods-image[data-v-22fcf626]{position:relative;width:100%;height:0;padding-bottom:100%;overflow:hidden;background:#fff}.diy-goods .goods-list .goods-item .goods-image[data-v-22fcf626]:after{content:"";display:block;margin-top:100%}.diy-goods .goods-list .goods-item .goods-image .image[data-v-22fcf626]{position:absolute;width:100%;height:100%;top:0;left:0;-o-object-fit:cover;object-fit:cover}.diy-goods .goods-list .goods-item .detail[data-v-22fcf626]{padding:%?8?%;background:#fff}.diy-goods .goods-list .goods-item .detail .goods-name[data-v-22fcf626]{min-height:%?68?%;line-height:1.3;white-space:normal;color:#484848;font-size:%?26?%}.diy-goods .goods-list .goods-item .detail .detail-price .goods-price[data-v-22fcf626]{margin-right:%?8?%}.diy-goods .goods-list .goods-item .detail .detail-price .line-price[data-v-22fcf626]{text-decoration:line-through}.diy-goods .goods-list.display__slide[data-v-22fcf626]{white-space:nowrap;font-size:0}.diy-goods .goods-list.display__slide .goods-item[data-v-22fcf626]{display:inline-block}.diy-goods .goods-list.display__list .goods-item[data-v-22fcf626]{float:left}.diy-goods .goods-list.column__2 .goods-item[data-v-22fcf626]{width:50%}.diy-goods .goods-list.column__3 .goods-item[data-v-22fcf626]{width:33.33333%}.diy-goods .goods-list.column__1 .goods-item[data-v-22fcf626]{width:100%;height:%?280?%;margin-bottom:%?12?%;padding:%?20?%;box-sizing:border-box;background:#fff;line-height:1.6}.diy-goods .goods-list.column__1 .goods-item[data-v-22fcf626]:last-child{margin-bottom:0}.diy-goods .goods-list.column__1 .goods-item_left[data-v-22fcf626]{display:flex;width:40%;background:#fff;align-items:center}.diy-goods .goods-list.column__1 .goods-item_left .image[data-v-22fcf626]{display:block;width:%?240?%;height:%?240?%}.diy-goods .goods-list.column__1 .goods-item_right[data-v-22fcf626]{position:relative;width:60%}.diy-goods .goods-list.column__1 .goods-item_right .goods-name[data-v-22fcf626]{margin-top:%?20?%;min-height:%?68?%;line-height:1.3;white-space:normal;color:#484848;font-size:%?26?%}.diy-goods .goods-list.column__1 .goods-item_desc[data-v-22fcf626]{margin-top:%?8?%}.diy-goods .goods-list.column__1 .desc-selling_point[data-v-22fcf626]{width:%?400?%;font-size:%?24?%;color:#e49a3d}.diy-goods .goods-list.column__1 .desc-goods_sales[data-v-22fcf626]{color:#999;font-size:%?24?%}.diy-goods .goods-list.column__1 .desc_footer[data-v-22fcf626]{font-size:%?24?%}.diy-goods .goods-list.column__1 .desc_footer .price_x[data-v-22fcf626]{margin-right:%?16?%;color:#f03c3c;font-size:%?30?%}.diy-goods .goods-list.column__1 .desc_footer .price_y[data-v-22fcf626]{text-decoration:line-through}',""]),t.exports=e},f034:function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var a=i(n("ba79")),r=i(n("a093")),o=i(n("8c21")),s=i(n("7261")),c=i(n("ab96")),d=i(n("db3b")),l=i(n("f0e0")),u=i(n("8f65")),f=i(n("f351")),p=i(n("c4e9")),v=i(n("f2a9")),m=i(n("ca7e")),g=i(n("9316")),y={name:"Page",components:{Search:a.default,Images:r.default,Banner:o.default,Window:s.default,Videos:c.default,Article:d.default,Notice:l.default,NavBar:u.default,Goods:f.default,Service:p.default,Blank:v.default,Guide:m.default,RichText:g.default},props:{items:{type:Array,default:function(){return[]}}}};e.default=y},f07c:function(t,e,n){"use strict";n.r(e);var i=n("1fc3"),a=n.n(i);for(var r in i)"default"!==r&&function(t){n.d(e,t,(function(){return i[t]}))}(r);e["default"]=a.a},f0e0:function(t,e,n){"use strict";n.r(e);var i=n("35be"),a=n("e21f");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"65db301a",null,!1,i["a"],o);e["default"]=c.exports},f1ae:function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-video",style:{padding:t.itemStyle.paddingTop+"px 0"}},[n("v-uni-video",{staticClass:"video",style:{height:t.itemStyle.height+"px"},attrs:{src:t.params.videoUrl,poster:t.params.poster,autoplay:1==t.params.autoplay,controls:!0}})],1)},r=[]},f2a9:function(t,e,n){"use strict";n.r(e);var i=n("3fff"),a=n("eb3a");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"7521eb20",null,!1,i["a"],o);e["default"]=c.exports},f351:function(t,e,n){"use strict";n.r(e);var i=n("7d2e"),a=n("2039");for(var r in a)"default"!==r&&function(t){n.d(e,t,(function(){return a[t]}))}(r);n("537f");var o,s=n("f0c5"),c=Object(s["a"])(a["default"],i["b"],i["c"],!1,null,"22fcf626",null,!1,i["a"],o);e["default"]=c.exports},f3b1:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */',""]),t.exports=e},f577:function(t,e,n){"use strict";var i=n("4ea4");Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var a=i(n("2d22")),r={name:"Images",props:{itemIndex:String,itemStyle:Object,params:Object,dataList:Array},mixins:[a.default],methods:{}};e.default=r},f89f:function(t,e,n){"use strict";var i;n.d(e,"b",(function(){return a})),n.d(e,"c",(function(){return r})),n.d(e,"a",(function(){return i}));var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("v-uni-view",{staticClass:"diy-navBar",style:{background:t.itemStyle.background,color:t.itemStyle.textColor}},[n("v-uni-view",{staticClass:"data-list",class:["avg-sm-"+t.itemStyle.rowsNum]},t._l(t.dataList,(function(e,i){return n("v-uni-view",{key:i,staticClass:"item-nav"},[n("v-uni-view",{staticClass:"nav-to",on:{click:function(n){arguments[0]=n=t.$handleEvent(n),t.onLink(e.link)}}},[n("v-uni-view",{staticClass:"item-image"},[n("v-uni-image",{staticClass:"image",attrs:{mode:"widthFix",src:e.imgUrl}})],1),n("v-uni-view",{staticClass:"item-text oneline-hide"},[t._v(t._s(e.text))])],1)],1)})),1)],1)},r=[]},f95b:function(t,e,n){var i=n("24fb");e=i(!1),e.push([t.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */\r\n/* 引入uView全局scss变量文件 */.diy-service[data-v-e52309a8]{position:fixed;z-index:999;right:calc(var(--window-right) + var(--right));bottom:calc(constant(safe-area-inset-bottom) + var(--window-bottom) + var(--bottom));bottom:calc(env(safe-area-inset-bottom) + var(--window-bottom) + var(--bottom))}.diy-service .service-icon[data-v-e52309a8]{padding:%?10?%}.diy-service .service-icon .image[data-v-e52309a8]{display:block;width:%?90?%;height:%?90?%;border-radius:50%;box-shadow:0 %?4?% %?20?% rgba(0,0,0,.1)}',""]),t.exports=e},f9eb:function(t,e,n){var i=n("f3b1");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("1b97f322",i,!0,{sourceMap:!1,shadowMode:!1})},fa2c:function(t,e,n){var i=n("11a9");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var a=n("4f06").default;a("72e38dc2",i,!0,{sourceMap:!1,shadowMode:!1})}}]);
|
import json
import shutil
import tempfile
import unittest
from pyhocon import ConfigFactory # noqa: F401
from typing import Any, List # noqa: F401
from databuilder import Scoped
from databuilder.loader.file_system_elasticsearch_json_loader import FSElasticsearchJSONLoader
from databuilder.models.table_elasticsearch_document import TableESDocument
class TestFSElasticsearchJSONLoader(unittest.TestCase):
def setUp(self):
# type: () -> None
self.temp_dir_path = tempfile.mkdtemp()
self.dest_file_name = '{}/test_file.json'.format(self.temp_dir_path)
self.file_mode = 'w'
config_dict = {'loader.filesystem.elasticsearch.file_path': self.dest_file_name,
'loader.filesystem.elasticsearch.mode': self.file_mode}
self.conf = ConfigFactory.from_dict(config_dict)
def tearDown(self):
# type: () -> None
shutil.rmtree(self.temp_dir_path)
def _check_results_helper(self, expected):
# type: (List[str]) -> None
"""
Helper function to compare results with expected outcome
:param expected: expected result
"""
with open(self.dest_file_name, 'r') as file:
for e in expected:
actual = file.readline().rstrip('\r\n')
self.assertDictEqual(json.loads(e), json.loads(actual))
self.assertFalse(file.readline())
def test_empty_loading(self):
# type: () -> None
"""
Test loading functionality with no data
"""
loader = FSElasticsearchJSONLoader()
loader.init(conf=Scoped.get_scoped_conf(conf=self.conf,
scope=loader.get_scope()))
loader.load(None) # type: ignore
loader.close()
self._check_results_helper(expected=[])
def test_loading_with_different_object(self):
# type: () -> None
"""
Test Loading functionality with a python Dict object
"""
loader = FSElasticsearchJSONLoader()
loader.init(conf=Scoped.get_scoped_conf(conf=self.conf,
scope=loader.get_scope()))
data = dict(database='test_database',
cluster='test_cluster',
schema_name='test_schema',
name='test_table',
key='test_table_key',
last_updated_epoch=123456789,
description='test_description',
column_names=['test_col1', 'test_col2'],
column_descriptions=['test_comment1', 'test_comment2'],
total_usage=10,
unique_usage=5,
tags=['test_tag1', 'test_tag2'])
with self.assertRaises(Exception) as context:
loader.load(data) # type: ignore
self.assertIn("Record not of type 'ElasticsearchDocument'!", str(context.exception))
loader.close()
def test_loading_with_single_object(self):
# type: () -> None
"""
Test Loading functionality with single python object
"""
loader = FSElasticsearchJSONLoader()
loader.init(conf=Scoped.get_scoped_conf(conf=self.conf,
scope=loader.get_scope()))
data = TableESDocument(database='test_database',
cluster='test_cluster',
schema_name='test_schema',
name='test_table',
key='test_table_key',
last_updated_epoch=123456789,
description='test_description',
column_names=['test_col1', 'test_col2'],
column_descriptions=['test_comment1', 'test_comment2'],
total_usage=10,
unique_usage=5,
tags=['test_tag1', 'test_tag2'])
loader.load(data)
loader.close()
expected = [
('{"key": "test_table_key", "column_descriptions": ["test_comment1", "test_comment2"], '
'"schema_name": "test_schema", "database": "test_database", "cluster": "test_cluster", '
'"column_names": ["test_col1", "test_col2"], "name": "test_table", '
'"last_updated_epoch": 123456789,'
'"description": "test_description", "unique_usage": 5, "total_usage": 10, '
'"tags": ["test_tag1", "test_tag2"]}')
]
self._check_results_helper(expected=expected)
def test_loading_with_list_of_objects(self):
# type: () -> None
"""
Test Loading functionality with list of objects.
Check to ensure all objects are added to file
"""
loader = FSElasticsearchJSONLoader()
loader.init(conf=Scoped.get_scoped_conf(conf=self.conf,
scope=loader.get_scope()))
data = [TableESDocument(database='test_database',
cluster='test_cluster',
schema_name='test_schema',
name='test_table',
key='test_table_key',
last_updated_epoch=123456789,
description='test_description',
column_names=['test_col1', 'test_col2'],
column_descriptions=['test_comment1', 'test_comment2'],
total_usage=10,
unique_usage=5,
tags=['test_tag1', 'test_tag2'])] * 5
for d in data:
loader.load(d)
loader.close()
expected = [
('{"key": "test_table_key", "column_descriptions": ["test_comment1", "test_comment2"], '
'"schema_name": "test_schema", "database": "test_database", "cluster": "test_cluster", '
'"column_names": ["test_col1", "test_col2"], "name": "test_table", '
'"last_updated_epoch": 123456789,'
'"description": "test_description", "unique_usage": 5, "total_usage": 10, '
'"tags": ["test_tag1", "test_tag2"]}')
] * 5
self._check_results_helper(expected=expected)
|
from omymodels import create_models
def test_unique_and_normal_index():
ddl = """
drop table if exists schema_name.approver_history ;
CREATE table schema_name.approver_history (
runid decimal(21) not null
,job_id decimal(21) not null
,id varchar(100) not null -- group_id or role_id
,approver varchar(100) not null
,status varchar(10) not null
,event_time timestamp not null default now()
,deny_reason varchar(1000) not null default 'none'
) ;
create unique index approver_history_pk on schema_name.approver_history (runid) ;
create index approver_history_ix2 on schema_name.approver_history (job_id) ;
create index approver_history_ix3 on schema_name.approver_history (id) ;"""
expected = """from gino import Gino
from sqlalchemy.sql import func
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy import Index
db = Gino(schema="schema_name")
class ApproverHistory(db.Model):
__tablename__ = 'approver_history'
runid = db.Column(db.Numeric(21), nullable=False)
job_id = db.Column(db.Numeric(21), nullable=False)
id = db.Column(db.String(100), nullable=False)
approver = db.Column(db.String(100), nullable=False)
status = db.Column(db.String(10), nullable=False)
event_time = db.Column(db.TIMESTAMP(), nullable=False, server_default=func.now())
deny_reason = db.Column(db.String(1000), nullable=False, server_default='none')
__table_args__ = (
UniqueConstraint(runid, name='approver_history_pk'),
Index('approver_history_ix2', job_id),
Index('approver_history_ix3', id))
"""
gino_models = create_models(ddl=ddl, dump=False)["code"]
assert expected == gino_models
|
import bcrypt from 'bcrypt';
import jwtSign from './token-service';
const { TOKEN_BODY_NAME } = process.env;
const TOKEN_COOKIE_NAME = process.env.TOKEN_COOKIE_NAME || 'NOT-XSRF-TOKEN';
const usersArray = [];
const getUserByUsername = (username, users) => {
let user;
for (let i = 0; i < users.length; i += 1) {
user = users[i];
if (user.username === username) {
return user;
}
}
return null;
};
const userRegisterHandler = async (ctx, next) => {
if (
!ctx.request.body.username
|| !ctx.request.body.password
|| !ctx.request.body.email
|| !ctx.request.body.name
) {
ctx.status = 400;
ctx.body = {
error: `expected an object with username, password, email, name but got: ${ctx.request.body}`,
};
return;
}
ctx.request.body.password = await bcrypt.hash(ctx.request.body.password, 5);
const user = getUserByUsername(ctx.request.body.username, usersArray);
if (!user) {
usersArray.push(ctx.request.body);
ctx.status = 200;
next();
} else {
ctx.status = 406;
ctx.body = {
error: 'User exists',
};
}
};
const userLoginHandler = async (ctx, next) => {
const user = await getUserByUsername(ctx.request.body.username, usersArray);
if (!user) {
ctx.status = 401;
ctx.body = {
error: 'bad username',
};
return;
}
const { password, ...userInfoWithoutPassword } = user;
if (await bcrypt.compare(ctx.request.body.password, password)) {
if (TOKEN_BODY_NAME == null) {
ctx.cookies.set(TOKEN_COOKIE_NAME, jwtSign(userInfoWithoutPassword), {
httpOnly: true,
});
ctx.status = 200;
} else {
const body = {};
body[TOKEN_BODY_NAME] = jwtSign(userInfoWithoutPassword);
ctx.body = body;
}
next();
} else {
ctx.status = 401;
ctx.body = {
error: 'bad password',
};
}
};
export { userRegisterHandler, userLoginHandler };
|
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['RECIPE_SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'core',
'user',
'recipe',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.environ.get('DB_HOST'),
'USER': os.environ.get('DB_USER'),
'NAME': os.environ.get('DB_NAME'),
'PASSWORD': os.environ.get('DB_PASS'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/vol/web/media'
STATIC_ROOT = '/vol/web/static'
AUTH_USER_MODEL = 'core.User'
|
var class_vulkan_render_pipeline_push_constants_layout_builder_1_1_vulkan_render_pipeline_push_constants_layout_builder_impl =
[
[ "VulkanRenderPipelinePushConstantsLayoutBuilderImpl", "class_vulkan_render_pipeline_push_constants_layout_builder_1_1_vulkan_render_pipeline_push_constants_layout_builder_impl.html#aa64aaa881f8dfb90c7e7763ed0898be1", null ],
[ "VulkanRenderPipelinePushConstantsLayoutBuilder", "class_vulkan_render_pipeline_push_constants_layout_builder_1_1_vulkan_render_pipeline_push_constants_layout_builder_impl.html#a9200bab22d3543a44e7526beadaf3a9a", null ]
];
|
// Fibonacci sequence
function fabonacci(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
return fabonacci(n - 1) + fabonacci(n - 2);
}
onmessage = function (val) {
switch (val.data) {
case 'start':
let result = fabonacci(42);
postMessage(result);
}
}
|
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
|
config = {
"interfaces": {
"google.ads.googleads.v0.services.RecommendationService": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": []
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 20000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetRecommendation": {
"timeout_millis": 600000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ApplyRecommendation": {
"timeout_millis": 600000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"DismissRecommendation": {
"timeout_millis": 600000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
}
}
}
}
}
|
import Phaser from 'phaser';
class GameScene extends Phaser.Scene {
constructor() {
super({ key: 'GameScene' });
}
init() {
this.loaded = false;
this.score = 0;
this.ended = 0;
this.highScore = localStorage.getItem('highScore');
this.events.once('start-game', ({ url, speed, endGame }) => {
this.playerSpeed = speed;
this.startGame(url);
this.endGame = endGame;
});
}
preload() {
this.load.image('image', '/assets/block.png');
}
create() {
this.cursors = this.input.keyboard.createCursorKeys();
this.blockOne = this.createBlock(this.genRandOne());
this.blockTwo = this.createBlock(this.genRandTwo());
this.scoreText = this.add.text(0, 0, `Score: ${this.score}`);
this.highScoreText = this.add.text(0, 20, `High Score: ${this.highScore}`);
}
update() {
if (this.loaded) {
if (this.cursors.left.isDown) {
this.player.setVelocityX(-220 * this.playerSpeed);
} else if (this.cursors.right.isDown) {
this.player.setVelocityX(220 * this.playerSpeed);
} else {
this.player.setVelocityX(0);
}
if (
this.blockOne.y > this.physics.world.bounds.height ||
this.blockTwo.y > this.physics.world.bounds.height
) {
this.score += 10;
this.reflectScore();
this.resetPos();
}
}
}
reflectScore() {
this.scoreText.setText(`Score: ${this.score}`);
if (this.score > this.highScore) this.highScore = this.score;
this.highScoreText.setText(`High Score: ${this.highScore}`);
}
createPlayer() {
let player = this.physics.add.sprite(
this.physics.world.bounds.centerX,
this.physics.world.bounds.bottom,
'player'
);
player.setGravityY(10);
player.setScale(0.2);
player.setBounce(0.5);
player.setCollideWorldBounds(true);
return player;
}
createBlock(posX) {
let platform = this.physics.add.sprite(posX, 0, 'image');
platform.setBounce(0.5);
return platform;
}
startGame(url) {
this.load.image('player', url);
this.load.once(Phaser.Loader.Events.COMPLETE, () => {
this.player = this.createPlayer();
this.addCollider(this.blockOne);
this.addCollider(this.blockTwo);
this.blockOne.setGravityY(10);
this.blockOne.setVelocityY(250);
this.blockTwo.setGravityY(10);
this.blockTwo.setVelocityY(250);
this.loaded = true;
});
this.load.start();
}
addCollider(platform) {
this.physics.add.collider(this.player, platform, () => {
if (!this.ended) {
alert('game over');
this.ended = 1;
this.endGame(this.score, this.game);
}
});
}
resetPos() {
this.blockOne.setY(0);
this.blockTwo.setY(0);
this.blockOne.setX(this.genRandOne());
this.blockTwo.setX(this.genRandTwo());
}
genRandOne() {
return (
Math.floor(Math.random() * this.physics.world.bounds.centerX) +
200 * Math.random()
);
}
genRandTwo() {
return (
(this.genRandOne() + this.physics.world.bounds.centerX) %
(this.physics.world.bounds.width - 100)
);
}
}
export default GameScene;
|
import argparse
from functools import partial, update_wrapper
from gdmixworkflow.common.constants import SINGLE_NODE, DISTRIBUTED
from gdmixworkflow.distributed_workflow import gdmix_distributed_workflow
from gdmixworkflow.single_node_workflow import run_gdmix_single_node
import os
import sys
def str2bool(v):
"""
handle argparse can't parse boolean well.
ref: https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse/36031646
"""
if isinstance(v, bool):
return v
if isinstance(v, str):
return v.lower() == 'true'
else:
raise argparse.ArgumentTypeError('Boolean or string value expected.')
def get_parser():
""" Creates an argument parser. """
parser = argparse.ArgumentParser()
parser.add_argument(
'--config_path',
type=str,
required=True,
help='path to gdmix config')
parser.add_argument(
'--mode',
type=str,
default=SINGLE_NODE,
help='distributed or single_node')
parser.add_argument(
'--jar_path',
type=str,
default="gdmix-data-all_2.11.jar",
help='local path to the gdmix-data jar for GDMix processing'
'intermediate data, single_node only')
parser.add_argument(
'--workflow_name',
type=str,
default="gdmix-workflow",
help='name for the generated zip file to upload to'
'Kubeflow Pipeline, distributed mode only')
parser.add_argument(
'--namespace',
type=str,
default="default",
help='Kubernetes namespace, distributed mode only')
parser.add_argument(
'--secret_name',
type=str,
default="default",
help='secret name to access storage, distributed mode only')
parser.add_argument(
'--image',
type=str,
default="linkedin/gdmix",
help='image used to launch gdmix jobs on Kubernetes, '
'distributed mode only')
parser.add_argument(
'--service_account',
type=str,
default="default",
help='service account to launch spark job, distributed mode only')
return parser
def main(args=None):
parser = get_parser()
args = parser.parse_args(args)
if args.mode == SINGLE_NODE:
try:
outputDir = run_gdmix_single_node(args.config_path, args.jar_path)
except RuntimeError as err:
print(str(err))
sys.exit(1)
print("""
------------------------
GDMix training is finished, results are saved to {}.
""".format(outputDir))
elif args.mode == DISTRIBUTED:
if not args.namespace:
print("ERROR: --namespace is required for distributed mode")
sys.exit(1)
def wrapped_partial(func, *args, **kwargs):
partial_func = partial(func, *args, **kwargs)
update_wrapper(partial_func, func)
return partial_func
func = wrapped_partial(
gdmix_distributed_workflow,
args.config_path,
args.namespace,
args.secret_name,
args.image,
args.service_account)
outputFileName = args.workflow_name + ".zip"
import kfp.compiler as compiler
compiler.Compiler().compile(func, outputFileName)
print("Workflow file is saved to {}".format(outputFileName))
else:
print("ERROR: --mode={} isn't supported.".format(args.mode))
sys.exit(1)
if __name__ == "__main__":
main()
|
import { withPluginApi } from "discourse/lib/plugin-api";
import { iconHTML } from "discourse-common/lib/icon-library";
function customBool(field) {
if (field) {
return Array.isArray(field) ? field.some(x => x === "t") : field === "t";
}
return false;
}
export default {
name: "add-holiday-flair",
initialize() {
withPluginApi("0.1", api => {
const usersOnHoliday = Discourse.Site.current().users_on_holiday;
api.decorateCooked(
el => {
if (!usersOnHoliday) {
return;
}
usersOnHoliday.forEach(username => {
$(el)
.find(`a.mention[href="/u/${username}"]`)
.not(".on-holiday")
.append(iconHTML("calendar-alt"))
.addClass("on-holiday");
});
},
{ id: "discourse-calendar-holiday-flair" }
);
api.addPosterIcon(cfs => {
const onHoliday = customBool(cfs.on_holiday);
if (!onHoliday) {
return;
}
return {
emoji: "desert_island",
className: "holiday",
title: "on holiday"
};
});
});
}
};
|
# -*- coding: utf-8 -*-
from Datenbank import Zeitungsdatenbank
print u"Modul chronam geladen"
print u"Initialisieren Sie bitte die Datenbank über Variable = chronam.Chronam()"
class Chronam(Zeitungsdatenbank):
#Für 'https://chroniclingamerica.loc.gov':
daten_init = {
'Datenbank_Url' : 'https://chroniclingamerica.loc.gov',
'Katalog_index_Url' : 'https://chroniclingamerica.loc.gov/search/pages/results/list/?date1=1863&date2=1863&language=&sequence=&lccn=&state=&rows=20&ortext=&proxtext=&year=&phrasetext=&andtext=&proxValue=&dateFilterType=yearRange&page=1149&sort=date',
'index_steuer_string' : 'page=1149',
'teiler' : '=',
'Datum_schema':'%b %d, %Y'}
re_muster_init = {
're_link_liste': '<ul class="results_list">.*?<\/ul>',
're_Eintraege' : '<li>.*?<\/li>',
're_download_link': '\"\/(.*?)\/;',
're_Erscheinungsdatum': "(\w*? \d+, \d\d\d\d)",
're_Zeitungsname': "<strong>(.*?)<\/strong>",
're_Erscheinungsort': '\((.*?)\)',
're_Seitennummer': "Image (\d+)",
're_Indexnummer': '%s\=(\d+)' %daten_init['index_steuer_string'].split(daten_init['teiler'])[0]}
def __init__(self, daten_init = daten_init, re_muster_init = re_muster_init):
super(Chronam, self).__init__()
print u"Die Anfangswerte für Chronic America werden geladen"
self.fill_values(daten_init)
self.fill_re_muster(re_muster_init)
print u"Die Datenbank zur Abfrage der Chronic America ist bereit"
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2019 The TARIAN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_ADDRESSBOOKPAGE_H
#define BITCOIN_QT_ADDRESSBOOKPAGE_H
#include <QDialog>
class AddressTableModel;
class OptionsModel;
namespace Ui
{
class AddressBookPage;
}
QT_BEGIN_NAMESPACE
class QItemSelection;
class QMenu;
class QModelIndex;
class QSortFilterProxyModel;
class QTableView;
QT_END_NAMESPACE
/** Widget that shows a list of sending or receiving addresses.
*/
class AddressBookPage : public QDialog
{
Q_OBJECT
public:
enum Tabs {
SendingTab = 0,
ReceivingTab = 1
};
enum Mode {
ForSelection, /**< Open address book to pick address */
ForEditing /**< Open address book for editing */
};
explicit AddressBookPage(Mode mode, Tabs tab, QWidget* parent);
~AddressBookPage();
void setModel(AddressTableModel* model);
const QString& getReturnValue() const { return returnValue; }
public Q_SLOTS:
void done(int retval);
private:
Ui::AddressBookPage* ui;
AddressTableModel* model;
Mode mode;
Tabs tab;
QString returnValue;
QSortFilterProxyModel* proxyModel;
QMenu* contextMenu;
QAction* deleteAction; // to be able to explicitly disable it
QString newAddressToSelect;
private Q_SLOTS:
/** Delete currently selected address entry */
void on_deleteAddress_clicked();
/** Create a new address for receiving coins and / or add a new address book entry */
void on_newAddress_clicked();
/** Copy address of currently selected address entry to clipboard */
void on_copyAddress_clicked();
/** Copy label of currently selected address entry to clipboard (no button) */
void onCopyLabelAction();
/** Edit currently selected address entry (no button) */
void onEditAction();
/** Export button clicked */
void on_exportButton_clicked();
/** Set button states based on selected tab and selection */
void selectionChanged();
/** Spawn contextual menu (right mouse menu) for address book entry */
void contextualMenu(const QPoint& point);
/** New entry/entries were added to address table */
void selectNewAddress(const QModelIndex& parent, int begin, int /*end*/);
Q_SIGNALS:
void sendCoins(QString addr);
};
#endif // BITCOIN_QT_ADDRESSBOOKPAGE_H
|
import csbuilder
from hks_pylib.done import Done
from csbuilder.scheme.scheme import Scheme
from csbuilder.scheme.result import SchemeResult
from csbuilder.cspacket.cspacket import CSPacket
from _simulator.manager.token import Token
from _simulator.manager.storage import Storage
from _simulator.protocol.definition import ThesisRoles, ThesisProtocols
from _simulator.protocol.definition import SearchClientStates, SearchServerStates
class FailureError(Exception):
...
@csbuilder.scheme(
ThesisProtocols.SEARCH,
ThesisRoles.SERVER,
SearchClientStates.REQUEST
)
class SearchServerScheme(Scheme):
def __init__(self) -> None:
super().__init__()
@csbuilder.response(SearchClientStates.IGNORE)
def resp_ignore(self, source: str, packet: CSPacket):
return SchemeResult(
None,
None,
False,
Done(False, reason="Ignore", message=packet.payload())
)
@csbuilder.response(SearchClientStates.REQUEST)
def resp_request(self, source: str, packet: CSPacket):
if self.is_running():
return self.ignore(source)
payload = packet.payload()
failure_reason = None
failure_packet = self.generate_packet(SearchServerStates.FAILURE)
try:
token, filename = payload.decode().split(" ")
try:
username = Token.degenerate(token)
except TimeoutError:
raise FailureError("Expired token")
except Exception:
raise FailureError("Invalid token")
path = Storage.get_path(username, filename)
if path is None:
raise FailureError("File doesn't found")
except ValueError:
raise FailureError("Invalid payload")
except FailureError as e:
failure_reason = str(e)
failure_packet.payload(failure_reason.encode())
except Exception as e:
failure_reason = "Unknown error ({})".format(e)
failure_packet.payload(b"Unknown error")
if failure_reason:
return SchemeResult(
source,
failure_packet,
False,
Done(False, reason=failure_reason)
)
token = Token.generate(path, timeout=900)
success_packet = self.generate_packet(SearchServerStates.SUCCESS)
success_packet.payload(token.encode())
return SchemeResult(
source,
success_packet,
False,
Done(True, token=token)
)
|
from pythonforandroid.recipe import PythonRecipe
class IdnaRecipe(PythonRecipe):
name = 'idna'
version = '2.6'
url = 'https://github.com/kjd/idna/archive/v{version}.tar.gz'
depends = [('python2', 'python3crystax'), 'setuptools']
call_hostpython_via_targetpython = False
recipe = IdnaRecipe()
|
import angr
import logging
print "WARNING: THIS EXAMPLE IS BROKEN RIGHT NOW"
def main():
p = angr.Project("r200", auto_load_libs=False)
sm = p.factory.simulation_manager()
# merge all states every time we hit the bottom of the outer loop
sm.use_technique(angr.exploration_techniques.ManualMergepoint(0x4007FD, wait_counter=9999))
# avoid the antidebug traps, go to puts("Nice!")
sm.use_technique(angr.exploration_techniques.Explorer(find=0x400936, avoid=(0x40085D, 0x400882)))
# go!
sm.run()
return sm.one_found.posix.dumps(0).split('\n')[0]
def test():
assert main() == 'rotors'
if __name__ == '__main__':
logging.getLogger('angr.manager').setLevel('DEBUG')
logging.getLogger('angr.exploration_techniques.manual_mergepoint').setLevel('DEBUG')
print main()
|
#include <no_macros.h>
/* Component types */
typedef struct {
double x, y;
} Position, Velocity;
/* Implement a simple move system */
void Move(ecs_iter_t *it) {
/* Get the two columns from the system signature */
Position *p = ecs_term_w_size(it, sizeof(Position), 1);
Velocity *v = ecs_term_w_size(it, sizeof(Velocity), 2);
for (int i = 0; i < it->count; i ++) {
p[i].x += v[i].x;
p[i].y += v[i].y;
/* Print something to the console so we can see the system is being
* invoked */
printf("%s moved to {.x = %f, .y = %f}\n",
ecs_get_name(it->world, it->entities[i]),
p[i].x, p[i].y);
}
}
int main(int argc, char *argv[]) {
/* Create the world, pass arguments for overriding the number of threads,fps
* or for starting the admin dashboard (see flecs.h for details). */
ecs_world_t *world = ecs_init_w_args(argc, argv);
/* Register components */
ecs_entity_t pos = ecs_component_init(world, &(ecs_component_desc_t){
.entity.name = "Position",
.size = sizeof(Position),
.alignment = ECS_ALIGNOF(Position)
});
ecs_entity_t vel = ecs_component_init(world, &(ecs_component_desc_t){
.entity.name = "Velocity",
.size = sizeof(Velocity),
.alignment = ECS_ALIGNOF(Velocity)
});
/* Register system */
ecs_system_init(world, &(ecs_system_desc_t){
.entity = {.name = "Move", .add = {EcsOnUpdate} },
.query.filter.terms = {{.id = pos}, {.id = vel}},
.callback = Move
});
/* Create entity with name MyEntity and components position & velocity */
ecs_entity_t e = ecs_entity_init(world, &(ecs_entity_desc_t){
.name = "MyEntity",
.add = {pos, vel}
});
/* Set values for entity. */
ecs_set_id(world, e, pos, sizeof(Position), &(Position){0, 0});
ecs_set_id(world, e, vel, sizeof(Velocity), &(Velocity){1, 1});
/* Set target FPS for main loop to 1 frame per second */
ecs_set_target_fps(world, 1);
printf("Application move_system is running, press CTRL-C to exit...\n");
/* Run systems */
while ( ecs_progress(world, 0));
/* Cleanup */
return ecs_fini(world);
}
|
// blnk.c
// 2019-02-20 Markku-Juhani O. Saarinen <mjos@pqshield.com>
// Copyright (C) 2019, PQShield Ltd. Please see LICENSE.
// The BLNK2 "core" state manipulation functions.
#include "blnk.h"
// Initialize with given rate and number of rounds
void blnk_clr(blnk_t *ctx, size_t rate, uint8_t rounds)
{
size_t i;
for (i = 0; i < BLNK_BLOCK; i++)
ctx->st.u8[i] = 0;
ctx->pos = 0;
ctx->rate = rate;
ctx->rounds = rounds;
}
// End a data element (compulsory between different domain types)
void blnk_fin(blnk_t *ctx, blnk_dom_t dom)
{
const uint8_t pad[1] = { 0x01 };
blnk_put(ctx, dom, pad, 1); // padding bit
if ((dom & BLNK_FULL) == 0) { // not full-state ?
ctx->st.u8[ctx->rate - 1] ^= 0x80; // indicate capacity
}
BLNK_PI(&ctx->st, dom | BLNK_LAST, ctx->rounds); // finalize
ctx->pos = 0;
}
// Absorb data
void blnk_put(blnk_t *ctx, blnk_dom_t dom, const void *in, size_t len)
{
size_t i, j, r;
i = ctx->pos;
r = dom & BLNK_FULL ? BLNK_BLOCK : ctx->rate; // full-state ?
for (j = 0; j < len; j++) {
if (i >= r) {
BLNK_PI(&ctx->st, dom, ctx->rounds);
i = 0;
}
ctx->st.u8[i++] ^= ((const uint8_t *) in)[j];
}
ctx->pos = i;
}
// Squeeze data
void blnk_get(blnk_t *ctx, blnk_dom_t dom, void *out, size_t len)
{
size_t i, j, r;
i = ctx->pos;
r = ctx->rate;
for (j = 0; j < len; j++) {
if (i >= r) {
BLNK_PI(&ctx->st, dom, ctx->rounds);
i = 0;
}
((uint8_t *) out)[j] = ctx->st.u8[i++];
}
ctx->pos = i;
}
// Encrypt data
void blnk_enc(blnk_t *ctx, blnk_dom_t dom,
void *out, const void *in, size_t len)
{
size_t i, j, r;
i = ctx->pos;
r = ctx->rate;
for (j = 0; j < len; j++) {
if (i >= r) {
BLNK_PI(&ctx->st, dom, ctx->rounds);
i = 0;
}
ctx->st.u8[i] ^= ((const uint8_t *) in)[j];
((uint8_t *) out)[j] = ctx->st.u8[i++];
}
ctx->pos = i;
}
// Decrypt data
void blnk_dec(blnk_t *ctx, blnk_dom_t dom,
void *out, const void *in, size_t len)
{
size_t i, j, r;
uint8_t t;
i = ctx->pos;
r = ctx->rate;
for (j = 0; j < len; j++) {
if (i >= r) {
BLNK_PI(&ctx->st, dom, ctx->rounds);
i = 0;
}
t = ((const uint8_t *) in)[j];
((uint8_t *) out)[j] = ctx->st.u8[i] ^ t;
ctx->st.u8[i++] = t;
}
ctx->pos = i;
}
// Compare to output (0 == equal)
int blnk_cmp(blnk_t *ctx, blnk_dom_t dom, const void *in, size_t len)
{
size_t i, j, r;
uint8_t t;
i = ctx->pos;
r = ctx->rate;
t = 0;
for (j = 0; j < len; j++) {
if (i >= r) {
BLNK_PI(&ctx->st, dom, ctx->rounds);
i = 0;
}
t |= ((const uint8_t *) in)[j] ^ ctx->st.u8[i++];
}
ctx->pos = i;
return t != 0;
}
// Ratchet for forward security
void blnk_ratchet(blnk_t *ctx)
{
size_t i, r;
r = ctx->rate;
for (i = 0; i < r; i++) {
ctx->st.u8[i] = 0;
}
ctx->pos = 0;
}
|
import React from 'react';
import { assert } from 'chai';
import { createMount, findOutermostIntrinsic, getClasses } from '@material-ui/core/test-utils';
import Slide from '../Slide';
import createMuiTheme from '../styles/createMuiTheme';
import Paper from '../Paper';
import Modal from '../Modal';
import Drawer, { getAnchor, isHorizontal } from './Drawer';
describe('<Drawer />', () => {
let mount;
let classes;
before(() => {
mount = createMount();
classes = getClasses(
<Drawer>
<div />
</Drawer>,
);
});
after(() => {
mount.cleanUp();
});
describe('prop: variant=temporary', () => {
it('should render a Modal', () => {
const wrapper = mount(
<Drawer>
<div />
</Drawer>,
);
assert.strictEqual(wrapper.find(Modal).exists(), true);
});
it('should render Slide > Paper inside the Modal', () => {
const wrapper = mount(
<Drawer open>
<div />
</Drawer>,
);
const modal = wrapper.find(Modal);
const slide = modal.find(Slide);
assert.strictEqual(slide.exists(), true);
const paper = slide.find(Paper);
assert.strictEqual(paper.exists(), true);
assert.strictEqual(paper.hasClass(classes.paper), true);
});
describe('transitionDuration property', () => {
const transitionDuration = {
enter: 854,
exit: 2967,
};
it('should be passed to Slide', () => {
const wrapper = mount(
<Drawer open transitionDuration={transitionDuration}>
<div />
</Drawer>,
);
assert.strictEqual(wrapper.find(Slide).props().timeout, transitionDuration);
});
it("should be passed to to Modal's BackdropTransitionDuration when open=true", () => {
const wrapper = mount(
<Drawer open transitionDuration={transitionDuration}>
<div />
</Drawer>,
);
assert.strictEqual(
wrapper.find(Modal).props().BackdropProps.transitionDuration,
transitionDuration,
);
});
});
it("should override Modal's BackdropTransitionDuration from property when specified", () => {
const testDuration = 335;
const wrapper = mount(
<Drawer BackdropTransitionDuration={testDuration}>
<div />
</Drawer>,
);
assert.strictEqual(wrapper.find(Modal).props().BackdropTransitionDuration, testDuration);
});
it('should set the custom className for Modal when variant is temporary', () => {
const wrapper = mount(
<Drawer className="woofDrawer" variant="temporary">
<h1>Hello</h1>
</Drawer>,
);
const modal = wrapper.find('Modal');
assert.strictEqual(modal.hasClass('woofDrawer'), true);
});
it('should set the Paper className', () => {
const wrapper = mount(
<Drawer classes={{ paper: 'woofDrawer' }} open>
<h1>Hello</h1>
</Drawer>,
);
const paper = wrapper.find(Paper);
assert.strictEqual(paper.hasClass(classes.paper), true);
assert.strictEqual(paper.hasClass('woofDrawer'), true);
});
it('should be closed by default', () => {
const wrapper = mount(
<Drawer>
<h1>Hello</h1>
</Drawer>,
);
const modal = wrapper.find('Modal');
assert.strictEqual(modal.props().open, false);
});
describe('opening and closing', () => {
const drawerElement = (
<Drawer>
<h1>Hello</h1>
</Drawer>
);
it('should start closed', () => {
const wrapper = mount(drawerElement);
assert.strictEqual(wrapper.find('Modal').props().open, false);
});
it('should open and close', () => {
const wrapper = mount(drawerElement);
wrapper.setProps({ open: true });
wrapper.update();
assert.strictEqual(wrapper.find('Slide').props().in, true);
wrapper.setProps({ open: false });
wrapper.update();
assert.strictEqual(wrapper.find('Slide').props().in, false);
});
});
});
describe('prop: variant=persistent', () => {
const drawerElement = (
<Drawer variant="persistent">
<h1>Hello</h1>
</Drawer>
);
it('should render a div instead of a Modal when persistent', () => {
const wrapper = mount(drawerElement);
const root = findOutermostIntrinsic(wrapper);
assert.strictEqual(root.type(), 'div');
assert.strictEqual(root.hasClass(classes.docked), true);
});
it('should render Slide > Paper inside the div', () => {
const wrapper = mount(drawerElement);
const div = wrapper.find('div').first();
const slide = div.childAt(0);
assert.strictEqual(slide.length, 1);
assert.strictEqual(slide.type(), Slide);
const paper = findOutermostIntrinsic(slide);
assert.strictEqual(paper.exists(), true);
assert.strictEqual(paper.hasClass(classes.paper), true);
});
});
describe('prop: variant=permanent', () => {
const drawerElement = (
<Drawer variant="permanent">
<h1>Hello</h1>
</Drawer>
);
it('should render a div instead of a Modal when permanent', () => {
const wrapper = mount(drawerElement);
const root = wrapper.find(`.${classes.root}`);
assert.strictEqual(root.type(), 'div');
assert.strictEqual(root.hasClass(classes.docked), true);
});
it('should render div > Paper inside the div', () => {
const wrapper = mount(drawerElement);
const root = wrapper.find(`div.${classes.root}`);
assert.strictEqual(root.exists(), true);
});
});
describe('slide direction', () => {
it('should return the opposing slide direction', () => {
const wrapper = mount(
<Drawer open>
<div />
</Drawer>,
);
wrapper.setProps({ anchor: 'left' });
assert.strictEqual(wrapper.find('Slide').props().direction, 'right');
wrapper.setProps({ anchor: 'right' });
assert.strictEqual(wrapper.find('Slide').props().direction, 'left');
wrapper.setProps({ anchor: 'top' });
assert.strictEqual(wrapper.find('Slide').props().direction, 'down');
wrapper.setProps({ anchor: 'bottom' });
assert.strictEqual(wrapper.find('Slide').props().direction, 'up');
});
});
describe('Right To Left', () => {
it('should switch left and right anchor when theme is right-to-left', () => {
const theme = createMuiTheme({
direction: 'rtl',
});
const wrapper = mount(
<Drawer open theme={theme}>
<div />
</Drawer>,
);
wrapper.setProps({ anchor: 'left' });
// slide direction for left is right, if left is switched to right, we should get left
assert.strictEqual(wrapper.find('Slide').props().direction, 'left');
wrapper.setProps({ anchor: 'right' });
// slide direction for right is left, if right is switched to left, we should get right
assert.strictEqual(wrapper.find('Slide').props().direction, 'right');
});
});
describe('isHorizontal', () => {
it('should recognize left and right as horizontal swiping directions', () => {
assert.strictEqual(isHorizontal({ anchor: 'left' }), true);
assert.strictEqual(isHorizontal({ anchor: 'right' }), true);
assert.strictEqual(isHorizontal({ anchor: 'top' }), false);
assert.strictEqual(isHorizontal({ anchor: 'bottom' }), false);
});
});
describe('getAnchor', () => {
it('should return the anchor', () => {
const theme = createMuiTheme({
direction: 'ltr',
});
assert.strictEqual(getAnchor({ anchor: 'left', theme }), 'left');
assert.strictEqual(getAnchor({ anchor: 'right', theme }), 'right');
assert.strictEqual(getAnchor({ anchor: 'top', theme }), 'top');
assert.strictEqual(getAnchor({ anchor: 'bottom', theme }), 'bottom');
});
it('should switch left/right if RTL is enabled', () => {
const theme = createMuiTheme({
direction: 'rtl',
});
assert.strictEqual(getAnchor({ anchor: 'left', theme }), 'right');
assert.strictEqual(getAnchor({ anchor: 'right', theme }), 'left');
});
});
});
|
// == Import npm
import React from 'react';
import PropTypes from 'prop-types';
// == Import
import './styles.scss';
// == Composant
const Result = ({ currency, value }) => (
<div className="result">
<p className="result__number">{value.toFixed(2)}</p>
<p className="result__currency">{currency}</p>
</div>
);
Result.propTypes = {
currency: PropTypes.string.isRequired,
value: PropTypes.number.isRequired,
};
// == Export
export default Result;
|
import bpy
from datetime import datetime
from os import path
from subprocess import call, check_output
from time import time
import meta
def export_still(options):
export_directory = bpy.path.abspath("//")
image_directory = path.join(export_directory, "rendered_frames")
ffmpeg_input_options = [
'ffmpeg',
'-y',
"-f", "image2",
"-pattern_type", "glob",
"-framerate", "24",
"-i", path.join(image_directory, "*.png")
]
export_thumbnail_still(ffmpeg_input_options, export_directory)
export_png(ffmpeg_input_options, export_directory)
export_jpg(ffmpeg_input_options, export_directory)
def export_thumbnail_still(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting Thumbnail"})
benchmark = time()
export_file = path.join(export_directory, "thumbnail.png")
ffmpeg_call = ffmpeg_input_options + [
"-vf", "scale=480:-1",
export_file
]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"thumbnail": {
"filePath": "thumbnail.png",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_jpg(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting JPG"})
benchmark = time()
export_file = path.join(export_directory, "still.jpg")
ffmpeg_call = ffmpeg_input_options + [export_file]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"jpg": {
"filePath": "still.jpg",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_png(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting PNG"})
benchmark = time()
export_file = path.join(export_directory, "still.png")
ffmpeg_call = ffmpeg_input_options + [export_file]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"png": {
"filePath": "still.png",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_animation(options):
# TODO: Properly model separation between thumbnail and final exporting ?
export_directory = bpy.path.abspath("//")
image_directory = path.join(export_directory, "rendered_frames")
ffmpeg_input_options = [
"ffmpeg",
"-y",
"-f", "image2",
"-pattern_type", "glob",
"-framerate", "24",
"-i", path.join(image_directory, "*.png")
]
export_thumbnail_animation(ffmpeg_input_options, export_directory)
export_mp4(ffmpeg_input_options, export_directory)
export_ogv(ffmpeg_input_options, export_directory)
export_webm(ffmpeg_input_options, export_directory)
export_gif(ffmpeg_input_options, export_directory)
export_zip(image_directory, export_directory)
def export_thumbnail_animation(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting Thumbnail"})
benchmark = time()
# TODO: Use better algorithm if available like in export_gif
export_file = path.join(export_directory, "thumbnail.gif")
ffmpeg_call = ffmpeg_input_options + [
"-vf", "scale=480:-1",
"-gifflags", "+transdiff",
export_file
]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"thumbnail": {
"filePath": "thumbnail.gif",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_mp4(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting MP4"})
benchmark = time()
export_file = path.join(export_directory, "animation.mp4")
ffmpeg_call = ffmpeg_input_options + [
"-c:v", "libx264",
"-preset", "slow",
"-crf", "4",
export_file
]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"mp4": {
"filePath": "animation.mp4",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_ogv(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting OGV"})
benchmark = time()
export_file = path.join(export_directory, "animation.ogv")
ffmpeg_call = ffmpeg_input_options + [
"-codec:v", "libtheora",
"-qscale:v", "7",
export_file
]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"ogv": {
"filePath": "animation.ogv",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_webm(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting WEBM"})
benchmark = time()
export_file = path.join(export_directory, "animation.webm")
ffmpeg_call = ffmpeg_input_options + [
"-c:v", "libvpx",
"-crf", "4",
"-b:v", "1M",
export_file
]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"webm": {
"filePath": "animation.webm",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_gif(ffmpeg_input_options, export_directory):
meta.write({"processing": "Exporting GIF"})
benchmark = time()
ffmpeg_version = check_output(["ffmpeg", "-version"]).decode().split()[2]
ffmpeg_version_major = int(ffmpeg_version.split(".")[0])
ffmpeg_version_minor = int(ffmpeg_version.split(".")[1])
export_file = path.join(export_directory, "animation.gif")
if ffmpeg_version_major >= 2 and ffmpeg_version_minor >= 6:
# Only available in ffmpeg 2.6+ (eg. in Ubuntu 15.10, Fedora 22)
# http://blog.pkh.me/p/21-high-quality-gif-with-ffmpeg.html
palette_file = path.join(export_directory, "palette.png")
filters = "fps=15,scale=320:-1:flags=lanczos"
ffmpeg_palette_call = ffmpeg_input_options + [
"-vf", "{},palettegen".format(filters),
palette_file
]
ffmpeg_render_call = ffmpeg_input_options + [
"-i", palette_file,
"-lavfi", "{} [x]; [x][1:v] paletteuse".format(filters),
export_file
]
call(ffmpeg_palette_call)
call(ffmpeg_render_call)
else:
ffmpeg_call = ffmpeg_input_options + [
"-gifflags", "+transdiff",
export_file
]
call(ffmpeg_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"gif": {
"filePath": "animation.gif",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export_zip(image_directory, export_directory):
meta.write({"processing": "Exporting ZIP"})
benchmark = time()
export_file = path.join(export_directory, "animation.zip")
zip_call = [
"zip",
"-r9",
export_file,
path.join(image_directory, "")
]
call(zip_call)
filesize = path.getsize(export_file)
meta.write({
"processing": False,
"zip": {
"filePath": "animation.zip",
"exported": datetime.now().isoformat(),
"processingTime": time() - benchmark,
"fileSize": filesize
}
})
def export(options):
if bpy.context.scene.frame_end > bpy.context.scene.frame_start:
export_animation(options)
else:
export_still(options)
|
# -*- coding: utf-8 -*-
#
# sphinxcontrib-rubydomain-acceptancetest documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 25 13:27:18 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinxcontrib.phpdomain']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'sphinxcontrib-phpdomain'
copyright = u'2011, Mark Story'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'sphinxdoc'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'sphinxcontrib-phpdomain'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'sphinxcontrib-phpdomain.tex', u'sphinxcontrib-phpdomain Documentation',
u'Mark Story', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'sphinxcontrib-phpdomain', u'sphinxcontrib-phpdomain Documentation',
[u'Mark Story'], 1)
]
|
const Discord = require('discord.js');
const ms = require('ms');
exports.run = (client, msg, args, lang) => {
const reason = args.slice(2).join(' ');
const time = args.slice(1, 2).join(' ');
let user = msg.mentions.users.first();
const membermention = msg.mentions.members.first();
const botconfs = client.botconfs.get('botconfs');
const tableload = client.guildconfs.get(msg.guild.id);
if (!user) {
try {
if (!msg.guild.members.get(args.slice(0, 1).join(' '))) throw new Error('User not found!');
user = msg.guild.members.get(args.slice(0, 1).join(' '));
user = user.user;
} catch (error) {
return msg.reply(lang.ban_idcheck);
}
}
if (user === msg.author) return msg.channel.send(lang.ban_yourself);
if (!time) return msg.reply('No time given');
if (!reason) return msg.reply(lang.ban_noinput);
if (!msg.guild.member(user).bannable) return msg.reply(lang.ban_nopermission);
msg.guild.ban(user);
const bantime = ms(args.slice(1, 2).join(' '));
if (typeof bantime === 'undefined') return msg.channel.send(lang.temporaryban_invalidtimeformat);
const banned = lang.temporaryban_banned.replace('%usertag', user.tag).replace('%bantime', ms(bantime));
const banembed = new Discord.RichEmbed()
.setColor('#99ff66')
.setDescription(`✅ ${banned}`);
msg.channel.send({
embed: banembed
});
const bandescription = lang.temporaryban_bandescription.replace('%usertag', `${user.username}#${user.discriminator}`).replace('%userid', user.id).replace('%reason', reason)
.replace('%bantime', ms(bantime));
const embed = new Discord.RichEmbed()
.setAuthor(`${lang.temporaryban_bannedby} ${msg.author.username}${msg.author.discriminator}`, msg.author.displayAvatarURL)
.setThumbnail(user.displayAvatarURL)
.setColor('#FF0000')
.setTimestamp()
.setDescription(bandescription);
if (tableload.tempbananonymous === 'true') {
const ananonymousembed = new Discord.RichEmbed()
.setAuthor(`${lang.temporaryban_bannedby} ${client.user.username}${client.user.discriminator}`, client.user.displayAvatarURL)
.setThumbnail(user.displayAvatarURL)
.setColor('#FF0000')
.setTimestamp()
.setDescription(bandescription);
user.send({
embed: ananonymousembed
});
} else {
user.send({
embed: embed
});
}
if (tableload.modlog === 'true') {
const modlogchannel = client.channels.get(tableload.modlogchannel);
modlogchannel.send({
embed: embed
});
}
botconfs.banscount += 1;
const bansettings = {
discordserverid: msg.guild.id,
memberid: membermention.id,
moderatorid: msg.author.id,
reason: reason,
bantime: bantime,
banCreatedAt: Date.now(),
banEndDate: Date.now() + bantime,
banscount: botconfs.banscount
};
botconfs.bans[botconfs.banscount] = bansettings;
client.botconfs.set('botconfs', botconfs);
setTimeout(async () => {
const fetchedbans = await msg.guild.fetchBans();
if (fetchedbans.has(user.id)) {
await msg.guild.unban(user);
const unbannedby = lang.unban_unbannedby.replace('%authortag', `${client.user.tag}`);
const automaticbandescription = lang.temporaryban_automaticbandescription.replace('%usertag', `${user.username}#${user.discriminator}`).replace('%userid', user.id);
const unmutedembed = new Discord.RichEmbed()
.setAuthor(unbannedby, client.user.displayAvatarURL)
.setThumbnail(user.displayAvatarURL)
.setColor('#FF0000')
.setTimestamp()
.setDescription(automaticbandescription);
if (tableload.modlog === 'true') {
const modlogchannel = client.channels.get(tableload.modlogchannel);
await modlogchannel.send({
embed: unmutedembed
});
}
}
delete botconfs.bans[botconfs.banscount];
client.botconfs.set('botconfs', botconfs);
}, bantime);
};
exports.conf = {
enabled: true,
guildOnly: true,
shortDescription: 'Ban',
aliases: ['tempban'],
userpermissions: ['BAN_MEMBERS'],
dashboardsettings: true
};
exports.help = {
name: 'temporaryban',
description: 'Ban an user temporary!',
usage: 'temporaryban {@User/UserID} {time (d, h, m, s)} {reason}',
example: ['temporaryban @Monkeyyy11#0001 1d Toxic behaviour'],
category: 'moderation',
botpermissions: ['BAN_MEMBERS', 'SEND_MESSAGES']
};
|
#ifndef GUIUtils_Included
#define GUIUtils_Included
#include "TemporaryComponent.h"
#include "Font.h"
#include "gobjects.h"
#include "ginteractors.h"
#include "gwindow.h"
#include <string>
#include <vector>
#include <tuple>
#include <memory>
#include <functional>
/* Line breaking mode. You can select between breaking at spaces or
* preserving all tokens as-is.
*/
enum class LineBreak {
BREAK_SPACES,
NO_BREAK_SPACES
};
/* Type: TextRender
*
* Object capable of rendering nicely-formatted text on the screen.
*/
class TextRender {
public:
/* Bounding rectangles for the text render. The first option gives the bounds that were
* provided at construction, which is useful if you want to make use of the full space
* available. The second is the bounding rectangle for where the text will actually
* draw, which is useful if you want to, say, draw a background behind just the part
* used.
*/
GRectangle bounds() const;
GRectangle computedBounds() const;
/* Intended font and actual font. */
MiniGUI::Font font() const;
MiniGUI::Font computedFont() const;
/* Draws this text render in the specified window. */
void draw(GWindow& window);
void draw(GCanvas* canvas);
/* Changes the horizontal text alignment. */
void alignLeft();
void alignCenterHorizontally();
/* Changes the vertical text alignment. */
void alignTop();
void alignCenterVertically();
/* Lays out a string to fit within the specified rectangle. The text might not fill up the
* entirety of that rectangle if it isn't long enough.
*
* This function will attempt to respect the font size specified in the font string, but may
* have to shrink the font size to get things to fit.
*/
static std::shared_ptr<TextRender> construct(const std::string& text,
const GRectangle& bounds,
const MiniGUI::Font& font,
LineBreak breakMode = LineBreak::BREAK_SPACES);
private:
TextRender() = default;
GRectangle mBounds; // Bounds specified by the user
GRectangle mComputedBounds; // Bounds actually occupied.
MiniGUI::Font mFont; // Font specified by the user
MiniGUI::Font mComputedFont; // Font actually used
/* Type representing a single line of text. */
struct TextLine {
std::string text;
GPoint baseline; // Where the baseline is
double width;
};
std::vector<TextLine> mLines;
/* Breaks the text apart into lines, shrinking the font until it fits in the given rectangle.
* Returns true on success.
*/
bool fitText(const std::vector<std::string>& tokens, LineBreak breakMode);
};
/* Type: LegendRender
*
* Object capable of rendering a nicely-formatted chart legend on the screen.
*/
class LegendRender {
public:
/* As before, there are two sets of bounds. The first is the bounds given in which the
* legend should be constructed. The second is what's actually occupied.
*/
GRectangle bounds() const;
GRectangle computedBounds() const;
void draw(GWindow& window);
/* Constructs a legend render in which each text string has the same color.
*
* The input lists of strings may be shorter than the input list of colors, but must
* not be longer.
*/
static std::shared_ptr<LegendRender> construct(const std::vector<std::string>& strings,
const std::vector<std::string>& colors,
const GRectangle& bounds,
const MiniGUI::Font& font,
const std::string& borderColor,
LineBreak breakMode = LineBreak::BREAK_SPACES);
/* Constructs a legend render in which each text string has an assigned colors
*
* The input lists of strings may be shorter than the input list of colors, but must
* not be longer.
*
* The specified font will have all its attributes preserved except color, which
* will change from item to item.
*/
static std::shared_ptr<LegendRender> construct(const std::vector<std::string>& strings,
const std::vector<std::string>& bulletColors,
const GRectangle& bounds,
const std::vector<std::string>& textColors,
const MiniGUI::Font& font,
const std::string& borderColor,
LineBreak breakMode = LineBreak::BREAK_SPACES);
private:
LegendRender() = default;
GRectangle mBounds;
GRectangle mComputedBounds;
std::vector<std::shared_ptr<TextRender>> mLines;
std::vector<std::string> mBulletColors;
std::string mBorderColor;
};
/* Type: LineGraphRender
*
* Object capable of rendering a nicely-formatted line graph on the screen.
*/
class LineGraphRender {
public:
GRectangle bounds() const;
void draw(GWindow& window);
/* Assembles the line graph renderer.
*
* The X and Y axes will assign labels to major tick marks. You can leave those labels
* blank if you'd like, but the number of labels will be inferred from the lengths of
* the label lists.
*
* You can have minor tick marks on each of the axes if you'd like by setting the
* major tick size to a number greater than zero.
*
* The data points provided should be normalized to a virtual space where (0, 0) is the
* origin and (1, 1) is the upper-right corner of the line graph. The lines don't have
* to have the same number of points or pass perfectly over the tick marks on the X
* axis.
*/
static std::shared_ptr<LineGraphRender> construct(const std::vector<std::vector<GPoint>>& lines,
const std::vector<std::string>& xLabels,
const std::vector<std::string>& yLabels,
std::size_t xMinorTicks,
std::size_t yMinorTicks,
const GRectangle& bounds,
const MiniGUI::Font& xLabelFont,
const MiniGUI::Font& yLabelFont,
const std::vector<std::string>& lineColors,
const std::string& axisColors);
private:
LineGraphRender() = default;
/* Axis start and end points. */
GPoint mOrigin, mXEnd, mYEnd;
/* Line labels and fonts. */
std::vector<std::string> mXLabels, mYLabels;
MiniGUI::Font mXLabelFont, mYLabelFont;
/* Axis parameters. */
std::string mAxisColor;
std::size_t mXMinorTicks, mYMinorTicks;
/* The lines, in real rather than virtual space. */
std::vector<std::vector<GPoint>> mLines;
std::vector<std::string> mLineColors;
GRectangle mBounds;
/* Draws each component. */
void drawXAxis(GWindow& window) const;
void drawYAxis(GWindow& window) const;
void drawLines(GWindow& window) const;
};
/* Clears the display, resetting it to a specific color. */
void clearDisplay(GWindow& window, const std::string& backgroundColor);
void clearDisplay(GCanvas* canvas, const std::string& backgroundColor);
/* Given a coordinate on the Earth's surface, along with a centering coordinate, returns
* the (x, y) coordinates at which to display that coordinate in a Mollweide projection.
* The returned coordinates are in logical space ([-2, +2] x [-1, +1]) and will need to
* be converted to screen space before being displayed.
*
* The input longitudes and latitudes should be in degrees, not radians.
*/
std::tuple<double, double> mollweideProjectionOf(double latitude, double longitude,
double centerLongitude = 0.0,
double centerLatitude = 0.0);
/* Creates a slider bar in the SOUTH console that slides over a given year range. */
Temporary<GSlider> makeYearSlider(GWindow& window, int startYear, int endYear);
/* Creates, but does not install, a combo box containing all the files in a directory
* that pass the given filter, using the specified default.
*/
GComboBox* makeFileSelector(const std::string& baseDir,
const std::string& defaultOption,
std::function<bool(const std::string&)> filter);
/* Given a bounding box and an aspect ratio, returns the largest GRectangle
* that (1) fits within the bounding box and (2) has that aspect ratio.
*/
GRectangle fitToBounds(const GRectangle& bounds, double aspectRatio);
#endif
|
"""Parse a page and add a Link header to the request, which CloudFlare can use to push static media to an HTTP/2 client."""
from django.conf import settings
from django.contrib.staticfiles import storage
from django.contrib.staticfiles.templatetags import staticfiles
from django.core.files.storage import get_storage_class
from django.utils.functional import LazyObject
EXTENSION_AS = {
'js': 'script',
'css': 'style',
'png': 'image',
'jpg': 'image',
'jpeg': 'image',
'svg': 'image',
'gif': 'image',
'ttf': 'font',
'woff': 'font',
'woff2': 'font'
}
FILE_FILTER = getattr(settings, 'CLOUDFLARE_PUSH_FILTER', lambda x: True)
class FileCollector(object):
def __init__(self):
self.collection = []
def collect(self, path):
if not path.endswith('/') and FILE_FILTER(path.lower()):
self.collection.append(path)
def storage_factory(collector):
class DebugConfiguredStorage(LazyObject):
def _setup(self):
configured_storage_cls = get_storage_class(settings.STATICFILES_STORAGE)
class DebugStaticFilesStorage(configured_storage_cls):
def __init__(self, collector, *args, **kwargs):
super(DebugStaticFilesStorage, self).__init__(*args, **kwargs)
self.collector = collector
def url(self, path):
self.collector.collect(path)
return super(DebugStaticFilesStorage, self).url(path)
self._wrapped = DebugStaticFilesStorage(collector)
return DebugConfiguredStorage
def sort_urls(urls):
"""
Order URLs by extension.
This function accepts a list of URLs and orders them by their extension.
CSS files are sorted to the start of the list, then JS, then everything
else.
"""
order = {"css": 0, "js": 1}
urls.sort(key=lambda x: order.get(x.rsplit(".")[-1].lower(), 2))
return urls
def create_header_content(urls):
"""
Creates the content for the Link header.
"""
links = []
for url in urls[:10]:
ext = url.rsplit(".")[-1].lower()
if ext in EXTENSION_AS:
link = "<%s>; rel=preload; as=%s" % (url, EXTENSION_AS[ext])
else:
link = "<%s>; rel=preload" % (url,)
links.append(link)
return ", ".join(links)
def push_middleware(get_response):
def middleware(request):
collector = FileCollector()
storage.staticfiles_storage = staticfiles.staticfiles_storage = storage_factory(collector)()
response = get_response(request)
collection_copy = list(collector.collection) # For compatibility with 2.7.
urls = list(set(storage.staticfiles_storage.url(f) for f in collection_copy))
urls = sort_urls(urls)
response["Link"] = create_header_content(urls)
return response
return middleware
|
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP865.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp865',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS
0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x008d: 0x00ec, # LATIN SMALL LETTER I WITH GRAVE
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00f2, # LATIN SMALL LETTER O WITH GRAVE
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE
0x0098: 0x00ff, # LATIN SMALL LETTER Y WITH DIAERESIS
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE
0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE
0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR
0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00a4, # CURRENCY SIGN
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'%' # 0x0025 -> PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
u'\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xec' # 0x008d -> LATIN SMALL LETTER I WITH GRAVE
u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE
u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE
u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf2' # 0x0095 -> LATIN SMALL LETTER O WITH GRAVE
u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE
u'\xff' # 0x0098 -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE
u'\xa3' # 0x009c -> POUND SIGN
u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE
u'\u20a7' # 0x009e -> PESETA SIGN
u'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK
u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE
u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE
u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
u'\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE
u'\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR
u'\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR
u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK
u'\u2310' # 0x00a9 -> REVERSED NOT SIGN
u'\xac' # 0x00aa -> NOT SIGN
u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK
u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xa4' # 0x00af -> CURRENCY SIGN
u'\u2591' # 0x00b0 -> LIGHT SHADE
u'\u2592' # 0x00b1 -> MEDIUM SHADE
u'\u2593' # 0x00b2 -> DARK SHADE
u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
u'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
u'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
u'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
u'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
u'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
u'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
u'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
u'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
u'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
u'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
u'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
u'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
u'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
u'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0x00db -> FULL BLOCK
u'\u2584' # 0x00dc -> LOWER HALF BLOCK
u'\u258c' # 0x00dd -> LEFT HALF BLOCK
u'\u2590' # 0x00de -> RIGHT HALF BLOCK
u'\u2580' # 0x00df -> UPPER HALF BLOCK
u'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
u'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
u'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
u'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
u'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
u'\xb5' # 0x00e6 -> MICRO SIGN
u'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
u'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
u'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
u'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
u'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
u'\u221e' # 0x00ec -> INFINITY
u'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
u'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
u'\u2229' # 0x00ef -> INTERSECTION
u'\u2261' # 0x00f0 -> IDENTICAL TO
u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
u'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
u'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
u'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
u'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
u'\xf7' # 0x00f6 -> DIVISION SIGN
u'\u2248' # 0x00f7 -> ALMOST EQUAL TO
u'\xb0' # 0x00f8 -> DEGREE SIGN
u'\u2219' # 0x00f9 -> BULLET OPERATOR
u'\xb7' # 0x00fa -> MIDDLE DOT
u'\u221a' # 0x00fb -> SQUARE ROOT
u'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
u'\xb2' # 0x00fd -> SUPERSCRIPT TWO
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK
0x00a3: 0x009c, # POUND SIGN
0x00a4: 0x00af, # CURRENCY SIGN
0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b5: 0x00e6, # MICRO SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00bf: 0x00a8, # INVERTED QUESTION MARK
0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE
0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE
0x00e6: 0x0091, # LATIN SMALL LIGATURE AE
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ec: 0x008d, # LATIN SMALL LETTER I WITH GRAVE
0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE
0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS
0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE
0x00f2: 0x0095, # LATIN SMALL LETTER O WITH GRAVE
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x00f6, # DIVISION SIGN
0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE
0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x00ff: 0x0098, # LATIN SMALL LETTER Y WITH DIAERESIS
0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x20a7: 0x009e, # PESETA SIGN
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2310: 0x00a9, # REVERSED NOT SIGN
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
|
/**
* @file ipv4_acl.h
*
* @brief definitions related to IPv4 access control list handling
*
*/
#ifndef PTPD_IPV4_ACL_H_
#define PTPD_IPV4_ACL_H_
#define IN_RANGE(num, min,max) \
(num >= min && num <= max)
enum {
ACL_PERMIT_DENY,
ACL_DENY_PERMIT
};
typedef struct {
uint32_t network;
uint32_t bitmask;
uint16_t netmask;
uint32_t hitCount;
} AclEntry;
typedef struct {
int numEntries;
AclEntry* entries;
} MaskTable;
typedef struct {
MaskTable* permitTable;
MaskTable* denyTable;
int processingOrder;
uint32_t passedCounter;
uint32_t droppedCounter;
} Ipv4AccessList;
/* Parse string into AclEntry array */
int maskParser(const char* input, AclEntry* output);
/* Destroy an Ipv4AccessList structure */
void freeIpv4AccessList(Ipv4AccessList** acl);
/* Initialise an Ipv4AccessList structure */
Ipv4AccessList* createIpv4AccessList(const char* permitList, const char* denyList, int processingOrder);
/* Match on an IP address */
int matchIpv4AccessList(Ipv4AccessList* acl, const uint32_t addr);
/* Display the contents and hit counters of an access list */
void dumpIpv4AccessList(Ipv4AccessList* acl);
/* Clear counters */
void clearIpv4AccessListCounters(Ipv4AccessList* acl);
#endif /* PTPD_IPV4_ACL_H_ */
|
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Sascha Schumann <sascha@schumann.cx> |
| Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#ifdef PHP_WIN32
# include "win32/winutil.h"
# include "win32/time.h"
#else
# include <sys/time.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include "php_ini.h"
#include "SAPI.h"
#include "rfc1867.h"
#include "php_variables.h"
#include "php_session.h"
#include "ext/standard/php_random.h"
#include "ext/standard/php_var.h"
#include "ext/date/php_date.h"
#include "ext/standard/php_lcg.h"
#include "ext/standard/url_scanner_ex.h"
#include "ext/standard/info.h"
#include "zend_smart_str.h"
#include "ext/standard/url.h"
#include "ext/standard/basic_functions.h"
#include "ext/standard/head.h"
#include "mod_files.h"
#include "mod_user.h"
#ifdef HAVE_LIBMM
#include "mod_mm.h"
#endif
PHPAPI ZEND_DECLARE_MODULE_GLOBALS(ps)
static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra);
static int (*php_session_rfc1867_orig_callback)(unsigned int event, void *event_data, void **extra);
static void php_session_track_init(void);
/* SessionHandler class */
zend_class_entry *php_session_class_entry;
/* SessionHandlerInterface */
zend_class_entry *php_session_iface_entry;
/* SessionIdInterface */
zend_class_entry *php_session_id_iface_entry;
/* SessionUpdateTimestampHandler class */
zend_class_entry *php_session_update_timestamp_class_entry;
/* SessionUpdateTimestampInterface */
zend_class_entry *php_session_update_timestamp_iface_entry;
#define PS_MAX_SID_LENGTH 256
/* ***********
* Helpers *
*********** */
#define IF_SESSION_VARS() \
if (Z_ISREF_P(&PS(http_session_vars)) && Z_TYPE_P(Z_REFVAL(PS(http_session_vars))) == IS_ARRAY)
#define SESSION_CHECK_ACTIVE_STATE \
if (PS(session_status) == php_session_active) { \
php_error_docref(NULL, E_WARNING, "A session is active. You cannot change the session module's ini settings at this time"); \
return FAILURE; \
}
#define SESSION_CHECK_OUTPUT_STATE \
if (SG(headers_sent) && stage != ZEND_INI_STAGE_DEACTIVATE) { \
php_error_docref(NULL, E_WARNING, "Headers already sent. You cannot change the session module's ini settings at this time"); \
return FAILURE; \
}
#define APPLY_TRANS_SID (PS(use_trans_sid) && !PS(use_only_cookies))
static int php_session_send_cookie(void);
static int php_session_abort(void);
/* Initialized in MINIT, readonly otherwise. */
static int my_module_number = 0;
/* Dispatched by RINIT and by php_session_destroy */
static inline void php_rinit_session_globals(void) /* {{{ */
{
/* Do NOT init PS(mod_user_names) here! */
/* TODO: These could be moved to MINIT and removed. These should be initialized by php_rshutdown_session_globals() always when execution is finished. */
PS(id) = NULL;
PS(session_status) = php_session_none;
PS(in_save_handler) = 0;
PS(set_handler) = 0;
PS(mod_data) = NULL;
PS(mod_user_is_open) = 0;
PS(define_sid) = 1;
PS(session_vars) = NULL;
PS(module_number) = my_module_number;
ZVAL_UNDEF(&PS(http_session_vars));
}
/* }}} */
/* Dispatched by RSHUTDOWN and by php_session_destroy */
static inline void php_rshutdown_session_globals(void) /* {{{ */
{
/* Do NOT destroy PS(mod_user_names) here! */
if (!Z_ISUNDEF(PS(http_session_vars))) {
zval_ptr_dtor(&PS(http_session_vars));
ZVAL_UNDEF(&PS(http_session_vars));
}
if (PS(mod_data) || PS(mod_user_implemented)) {
zend_try {
PS(mod)->s_close(&PS(mod_data));
} zend_end_try();
}
if (PS(id)) {
zend_string_release(PS(id));
PS(id) = NULL;
}
if (PS(session_vars)) {
zend_string_release(PS(session_vars));
PS(session_vars) = NULL;
}
/* User save handlers may end up directly here by misuse, bugs in user script, etc. */
/* Set session status to prevent error while restoring save handler INI value. */
PS(session_status) = php_session_none;
}
/* }}} */
PHPAPI int php_session_destroy(void) /* {{{ */
{
int retval = SUCCESS;
if (PS(session_status) != php_session_active) {
php_error_docref(NULL, E_WARNING, "Trying to destroy uninitialized session");
return FAILURE;
}
if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
retval = FAILURE;
php_error_docref(NULL, E_WARNING, "Session object destruction failed");
}
php_rshutdown_session_globals();
php_rinit_session_globals();
return retval;
}
/* }}} */
PHPAPI void php_add_session_var(zend_string *name) /* {{{ */
{
IF_SESSION_VARS() {
zval *sess_var = Z_REFVAL(PS(http_session_vars));
SEPARATE_ARRAY(sess_var);
if (!zend_hash_exists(Z_ARRVAL_P(sess_var), name)) {
zval empty_var;
ZVAL_NULL(&empty_var);
zend_hash_update(Z_ARRVAL_P(sess_var), name, &empty_var);
}
}
}
/* }}} */
PHPAPI zval* php_set_session_var(zend_string *name, zval *state_val, php_unserialize_data_t *var_hash) /* {{{ */
{
IF_SESSION_VARS() {
zval *sess_var = Z_REFVAL(PS(http_session_vars));
SEPARATE_ARRAY(sess_var);
return zend_hash_update(Z_ARRVAL_P(sess_var), name, state_val);
}
return NULL;
}
/* }}} */
PHPAPI zval* php_get_session_var(zend_string *name) /* {{{ */
{
IF_SESSION_VARS() {
return zend_hash_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), name);
}
return NULL;
}
/* }}} */
static void php_session_track_init(void) /* {{{ */
{
zval session_vars;
zend_string *var_name = zend_string_init("_SESSION", sizeof("_SESSION") - 1, 0);
/* Unconditionally destroy existing array -- possible dirty data */
zend_delete_global_variable(var_name);
if (!Z_ISUNDEF(PS(http_session_vars))) {
zval_ptr_dtor(&PS(http_session_vars));
}
array_init(&session_vars);
ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
Z_ADDREF_P(&PS(http_session_vars));
zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
zend_string_release(var_name);
}
/* }}} */
static zend_string *php_session_encode(void) /* {{{ */
{
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
return NULL;
}
return PS(serializer)->encode();
} else {
php_error_docref(NULL, E_WARNING, "Cannot encode non-existent session");
}
return NULL;
}
/* }}} */
static int php_session_decode(zend_string *data) /* {{{ */
{
if (!PS(serializer)) {
php_error_docref(NULL, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
return FAILURE;
}
if (PS(serializer)->decode(ZSTR_VAL(data), ZSTR_LEN(data)) == FAILURE) {
php_session_destroy();
php_session_track_init();
php_error_docref(NULL, E_WARNING, "Failed to decode session object. Session has been destroyed");
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/*
* Note that we cannot use the BASE64 alphabet here, because
* it contains "/" and "+": both are unacceptable for simple inclusion
* into URLs.
*/
static char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
/* returns a pointer to the byte after the last valid character in out */
static size_t bin_to_readable(unsigned char *in, size_t inlen, char *out, char nbits) /* {{{ */
{
unsigned char *p, *q;
unsigned short w;
size_t len = inlen;
int mask;
int have;
p = (unsigned char *)in;
q = (unsigned char *)in + inlen;
w = 0;
have = 0;
mask = (1 << nbits) - 1;
while (inlen--) {
if (have < nbits) {
if (p < q) {
w |= *p++ << have;
have += 8;
} else {
/* consumed everything? */
if (have == 0) break;
/* No? We need a final round */
have = nbits;
}
}
/* consume nbits */
*out++ = hexconvtab[w & mask];
w >>= nbits;
have -= nbits;
}
*out = '\0';
return len;
}
/* }}} */
#define PS_EXTRA_RAND_BYTES 60
PHPAPI zend_string *php_session_create_id(PS_CREATE_SID_ARGS) /* {{{ */
{
unsigned char rbuf[PS_MAX_SID_LENGTH + PS_EXTRA_RAND_BYTES];
zend_string *outid;
/* Read additional PS_EXTRA_RAND_BYTES just in case CSPRNG is not safe enough */
if (php_random_bytes_throw(rbuf, PS(sid_length) + PS_EXTRA_RAND_BYTES) == FAILURE) {
return NULL;
}
outid = zend_string_alloc(PS(sid_length), 0);
ZSTR_LEN(outid) = bin_to_readable(rbuf, PS(sid_length), ZSTR_VAL(outid), (char)PS(sid_bits_per_character));
return outid;
}
/* }}} */
/* Default session id char validation function allowed by ps_modules.
* If you change the logic here, please also update the error message in
* ps_modules appropriately */
PHPAPI int php_session_valid_key(const char *key) /* {{{ */
{
size_t len;
const char *p;
char c;
int ret = SUCCESS;
for (p = key; (c = *p); p++) {
/* valid characters are a..z,A..Z,0..9 */
if (!((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == ','
|| c == '-')) {
ret = FAILURE;
break;
}
}
len = p - key;
/* Somewhat arbitrary length limit here, but should be way more than
anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
if (len == 0 || len > PS_MAX_SID_LENGTH) {
ret = FAILURE;
}
return ret;
}
/* }}} */
static zend_long php_session_gc(zend_bool immediate) /* {{{ */
{
int nrand;
zend_long num = -1;
/* GC must be done before reading session data. */
if ((PS(mod_data) || PS(mod_user_implemented))) {
if (immediate) {
PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &num);
return num;
}
nrand = (zend_long) ((float) PS(gc_divisor) * php_combined_lcg());
if (PS(gc_probability) > 0 && nrand < PS(gc_probability)) {
PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &num);
}
}
return num;
} /* }}} */
static int php_session_initialize(void) /* {{{ */
{
zend_string *val = NULL;
PS(session_status) = php_session_active;
if (!PS(mod)) {
PS(session_status) = php_session_disabled;
php_error_docref(NULL, E_WARNING, "No storage module chosen - failed to initialize session");
return FAILURE;
}
/* Open session handler first */
if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE
/* || PS(mod_data) == NULL */ /* FIXME: open must set valid PS(mod_data) with success */
) {
php_session_abort();
php_error_docref(NULL, E_WARNING, "Failed to initialize storage module: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return FAILURE;
}
/* If there is no ID, use session module to create one */
if (!PS(id) || !ZSTR_VAL(PS(id))[0]) {
if (PS(id)) {
zend_string_release(PS(id));
}
PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
if (!PS(id)) {
php_session_abort();
zend_throw_error(NULL, "Failed to create session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return FAILURE;
}
if (PS(use_cookies)) {
PS(send_cookie) = 1;
}
} else if (PS(use_strict_mode) && PS(mod)->s_validate_sid &&
PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == FAILURE) {
if (PS(id)) {
zend_string_release(PS(id));
}
PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
if (!PS(id)) {
PS(id) = php_session_create_id(NULL);
}
if (PS(use_cookies)) {
PS(send_cookie) = 1;
}
}
if (php_session_reset_id() == FAILURE) {
php_session_abort();
return FAILURE;
}
/* Read data */
php_session_track_init();
if (PS(mod)->s_read(&PS(mod_data), PS(id), &val, PS(gc_maxlifetime)) == FAILURE) {
php_session_abort();
/* FYI: Some broken save handlers return FAILURE for non-existent session ID, this is incorrect */
php_error_docref(NULL, E_WARNING, "Failed to read session data: %s (path: %s)", PS(mod)->s_name, PS(save_path));
return FAILURE;
}
/* GC must be done after read */
php_session_gc(0);
if (PS(session_vars)) {
zend_string_release(PS(session_vars));
PS(session_vars) = NULL;
}
if (val) {
if (PS(lazy_write)) {
PS(session_vars) = zend_string_copy(val);
}
php_session_decode(val);
zend_string_release(val);
}
return SUCCESS;
}
/* }}} */
static void php_session_save_current_state(int write) /* {{{ */
{
int ret = FAILURE;
if (write) {
IF_SESSION_VARS() {
if (PS(mod_data) || PS(mod_user_implemented)) {
zend_string *val;
val = php_session_encode();
if (val) {
if (PS(lazy_write) && PS(session_vars)
&& PS(mod)->s_update_timestamp
&& PS(mod)->s_update_timestamp != php_session_update_timestamp
&& ZSTR_LEN(val) == ZSTR_LEN(PS(session_vars))
&& !memcmp(ZSTR_VAL(val), ZSTR_VAL(PS(session_vars)), ZSTR_LEN(val))
) {
ret = PS(mod)->s_update_timestamp(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));
} else {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));
}
zend_string_release(val);
} else {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
}
}
if ((ret == FAILURE) && !EG(exception)) {
if (!PS(mod_user_implemented)) {
php_error_docref(NULL, E_WARNING, "Failed to write session data (%s). Please "
"verify that the current setting of session.save_path "
"is correct (%s)",
PS(mod)->s_name,
PS(save_path));
} else {
php_error_docref(NULL, E_WARNING, "Failed to write session data using user "
"defined save handler. (session.save_path: %s)", PS(save_path));
}
}
}
}
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data));
}
}
/* }}} */
static void php_session_normalize_vars() /* {{{ */
{
PS_ENCODE_VARS;
IF_SESSION_VARS() {
PS_ENCODE_LOOP(
if (Z_TYPE_P(struc) == IS_PTR) {
zval *zv = (zval *)Z_PTR_P(struc);
ZVAL_COPY_VALUE(struc, zv);
ZVAL_UNDEF(zv);
}
);
}
}
/* }}} */
/* *************************
* INI Settings/Handlers *
************************* */
static PHP_INI_MH(OnUpdateSaveHandler) /* {{{ */
{
ps_module *tmp;
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
tmp = _php_find_ps_module(ZSTR_VAL(new_value));
if (PG(modules_activated) && !tmp) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL, err_type, "Cannot find save handler '%s'", ZSTR_VAL(new_value));
}
return FAILURE;
}
/* "user" save handler should not be set by user */
if (!PS(set_handler) && tmp == ps_user_ptr) {
php_error_docref(NULL, E_RECOVERABLE_ERROR, "Cannot set 'user' save handler by ini_set() or session_module_name()");
return FAILURE;
}
PS(default_mod) = PS(mod);
PS(mod) = tmp;
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateSerializer) /* {{{ */
{
const ps_serializer *tmp;
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
tmp = _php_find_ps_serializer(ZSTR_VAL(new_value));
if (PG(modules_activated) && !tmp) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL, err_type, "Cannot find serialization handler '%s'", ZSTR_VAL(new_value));
}
return FAILURE;
}
PS(serializer) = tmp;
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateTransSid) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
if (!strncasecmp(ZSTR_VAL(new_value), "on", sizeof("on"))) {
PS(use_trans_sid) = (zend_bool) 1;
} else {
PS(use_trans_sid) = (zend_bool) atoi(ZSTR_VAL(new_value));
}
return SUCCESS;
}
/* }}} */
static PHP_INI_MH(OnUpdateSaveDir) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
/* Only do the safemode/open_basedir check at runtime */
if (stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) {
char *p;
if (memchr(ZSTR_VAL(new_value), '\0', ZSTR_LEN(new_value)) != NULL) {
return FAILURE;
}
/* we do not use zend_memrchr() since path can contain ; itself */
if ((p = strchr(ZSTR_VAL(new_value), ';'))) {
char *p2;
p++;
if ((p2 = strchr(p, ';'))) {
p = p2 + 1;
}
} else {
p = ZSTR_VAL(new_value);
}
if (PG(open_basedir) && *p && php_check_open_basedir(p)) {
return FAILURE;
}
}
return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateName) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
/* Numeric session.name won't work at all */
if ((!ZSTR_LEN(new_value) || is_numeric_string(ZSTR_VAL(new_value), ZSTR_LEN(new_value), NULL, NULL, 0))) {
int err_type;
if (stage == ZEND_INI_STAGE_RUNTIME || stage == ZEND_INI_STAGE_ACTIVATE || stage == ZEND_INI_STAGE_STARTUP) {
err_type = E_WARNING;
} else {
err_type = E_ERROR;
}
/* Do not output error when restoring ini options. */
if (stage != ZEND_INI_STAGE_DEACTIVATE) {
php_error_docref(NULL, err_type, "session.name cannot be a numeric or empty '%s'", ZSTR_VAL(new_value));
}
return FAILURE;
}
return OnUpdateStringUnempty(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateCookieLifetime) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
if (atol(ZSTR_VAL(new_value)) < 0) {
php_error_docref(NULL, E_WARNING, "CookieLifetime cannot be negative");
return FAILURE;
}
return OnUpdateLongGEZero(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateSessionLong) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
return OnUpdateLong(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateSessionString) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateSessionBool) /* {{{ */
{
SESSION_CHECK_OUTPUT_STATE;
SESSION_CHECK_ACTIVE_STATE;
return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateSidLength) /* {{{ */
{
zend_long val;
char *endptr = NULL;
SESSION_CHECK_OUTPUT_STATE;
SESSION_CHECK_ACTIVE_STATE;
val = ZEND_STRTOL(ZSTR_VAL(new_value), &endptr, 10);
if (endptr && (*endptr == '\0')
&& val >= 22 && val <= PS_MAX_SID_LENGTH) {
/* Numeric value */
PS(sid_length) = val;
return SUCCESS;
}
php_error_docref(NULL, E_WARNING, "session.configuration 'session.sid_length' must be between 22 and 256.");
return FAILURE;
}
/* }}} */
static PHP_INI_MH(OnUpdateSidBits) /* {{{ */
{
zend_long val;
char *endptr = NULL;
SESSION_CHECK_OUTPUT_STATE;
SESSION_CHECK_ACTIVE_STATE;
val = ZEND_STRTOL(ZSTR_VAL(new_value), &endptr, 10);
if (endptr && (*endptr == '\0')
&& val >= 4 && val <=6) {
/* Numeric value */
PS(sid_bits_per_character) = val;
return SUCCESS;
}
php_error_docref(NULL, E_WARNING, "session.configuration 'session.sid_bits_per_character' must be between 4 and 6.");
return FAILURE;
}
/* }}} */
static PHP_INI_MH(OnUpdateLazyWrite) /* {{{ */
{
SESSION_CHECK_ACTIVE_STATE;
SESSION_CHECK_OUTPUT_STATE;
return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
/* }}} */
static PHP_INI_MH(OnUpdateRfc1867Freq) /* {{{ */
{
int tmp;
tmp = zend_atoi(ZSTR_VAL(new_value), (int)ZSTR_LEN(new_value));
if(tmp < 0) {
php_error_docref(NULL, E_WARNING, "session.upload_progress.freq must be greater than or equal to zero");
return FAILURE;
}
if(ZSTR_LEN(new_value) > 0 && ZSTR_VAL(new_value)[ZSTR_LEN(new_value)-1] == '%') {
if(tmp > 100) {
php_error_docref(NULL, E_WARNING, "session.upload_progress.freq cannot be over 100%%");
return FAILURE;
}
PS(rfc1867_freq) = -tmp;
} else {
PS(rfc1867_freq) = tmp;
}
return SUCCESS;
} /* }}} */
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("session.save_path", "", PHP_INI_ALL, OnUpdateSaveDir, save_path, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.name", "PHPSESSID", PHP_INI_ALL, OnUpdateName, session_name, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.save_handler", "files", PHP_INI_ALL, OnUpdateSaveHandler)
STD_PHP_INI_BOOLEAN("session.auto_start", "0", PHP_INI_PERDIR, OnUpdateBool, auto_start, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_probability", "1", PHP_INI_ALL, OnUpdateSessionLong, gc_probability, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_divisor", "100", PHP_INI_ALL, OnUpdateSessionLong, gc_divisor, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.gc_maxlifetime", "1440", PHP_INI_ALL, OnUpdateSessionLong, gc_maxlifetime, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.serialize_handler", "php", PHP_INI_ALL, OnUpdateSerializer)
STD_PHP_INI_ENTRY("session.cookie_lifetime", "0", PHP_INI_ALL, OnUpdateCookieLifetime,cookie_lifetime, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_path", "/", PHP_INI_ALL, OnUpdateSessionString, cookie_path, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_domain", "", PHP_INI_ALL, OnUpdateSessionString, cookie_domain, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_secure", "0", PHP_INI_ALL, OnUpdateSessionBool, cookie_secure, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cookie_httponly", "0", PHP_INI_ALL, OnUpdateSessionBool, cookie_httponly, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.use_cookies", "1", PHP_INI_ALL, OnUpdateSessionBool, use_cookies, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.use_only_cookies", "1", PHP_INI_ALL, OnUpdateSessionBool, use_only_cookies, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.use_strict_mode", "0", PHP_INI_ALL, OnUpdateSessionBool, use_strict_mode, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.referer_check", "", PHP_INI_ALL, OnUpdateSessionString, extern_referer_chk, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cache_limiter", "nocache", PHP_INI_ALL, OnUpdateSessionString, cache_limiter, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.cache_expire", "180", PHP_INI_ALL, OnUpdateSessionLong, cache_expire, php_ps_globals, ps_globals)
PHP_INI_ENTRY("session.use_trans_sid", "0", PHP_INI_ALL, OnUpdateTransSid)
PHP_INI_ENTRY("session.sid_length", "32", PHP_INI_ALL, OnUpdateSidLength)
PHP_INI_ENTRY("session.sid_bits_per_character", "4", PHP_INI_ALL, OnUpdateSidBits)
STD_PHP_INI_BOOLEAN("session.lazy_write", "1", PHP_INI_ALL, OnUpdateLazyWrite, lazy_write, php_ps_globals, ps_globals)
/* Upload progress */
STD_PHP_INI_BOOLEAN("session.upload_progress.enabled",
"1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_enabled, php_ps_globals, ps_globals)
STD_PHP_INI_BOOLEAN("session.upload_progress.cleanup",
"1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_cleanup, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.prefix",
"upload_progress_", ZEND_INI_PERDIR, OnUpdateString, rfc1867_prefix, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.name",
"PHP_SESSION_UPLOAD_PROGRESS", ZEND_INI_PERDIR, OnUpdateString, rfc1867_name, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.freq", "1%", ZEND_INI_PERDIR, OnUpdateRfc1867Freq, rfc1867_freq, php_ps_globals, ps_globals)
STD_PHP_INI_ENTRY("session.upload_progress.min_freq",
"1", ZEND_INI_PERDIR, OnUpdateReal, rfc1867_min_freq,php_ps_globals, ps_globals)
/* Commented out until future discussion */
/* PHP_INI_ENTRY("session.encode_sources", "globals,track", PHP_INI_ALL, NULL) */
PHP_INI_END()
/* }}} */
/* ***************
* Serializers *
*************** */
PS_SERIALIZER_ENCODE_FUNC(php_serialize) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
IF_SESSION_VARS() {
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, Z_REFVAL(PS(http_session_vars)), &var_hash);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
}
return buf.s;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */
{
const char *endptr = val + vallen;
zval session_vars;
php_unserialize_data_t var_hash;
int result;
zend_string *var_name = zend_string_init("_SESSION", sizeof("_SESSION") - 1, 0);
ZVAL_NULL(&session_vars);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
result = php_var_unserialize(
&session_vars, (const unsigned char **)&val, (const unsigned char *)endptr, &var_hash);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (!result) {
zval_ptr_dtor(&session_vars);
ZVAL_NULL(&session_vars);
}
if (!Z_ISUNDEF(PS(http_session_vars))) {
zval_ptr_dtor(&PS(http_session_vars));
}
if (Z_TYPE(session_vars) == IS_NULL) {
array_init(&session_vars);
}
ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
Z_ADDREF_P(&PS(http_session_vars));
zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
zend_string_release(var_name);
return SUCCESS;
}
/* }}} */
#define PS_BIN_NR_OF_BITS 8
#define PS_BIN_UNDEF (1<<(PS_BIN_NR_OF_BITS-1))
#define PS_BIN_MAX (PS_BIN_UNDEF-1)
PS_SERIALIZER_ENCODE_FUNC(php_binary) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PS_ENCODE_VARS;
PHP_VAR_SERIALIZE_INIT(var_hash);
PS_ENCODE_LOOP(
if (ZSTR_LEN(key) > PS_BIN_MAX) continue;
smart_str_appendc(&buf, (unsigned char)ZSTR_LEN(key));
smart_str_appendl(&buf, ZSTR_VAL(key), ZSTR_LEN(key));
php_var_serialize(&buf, struc, &var_hash);
);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
return buf.s;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */
{
const char *p;
const char *endptr = val + vallen;
int namelen;
zend_string *name;
php_unserialize_data_t var_hash;
zval *current, rv;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
for (p = val; p < endptr; ) {
namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF);
if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
name = zend_string_init(p + 1, namelen, 0);
p += namelen + 1;
current = var_tmp_var(&var_hash);
if (php_var_unserialize(current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash)) {
ZVAL_PTR(&rv, current);
php_set_session_var(name, &rv, &var_hash);
} else {
zend_string_release(name);
php_session_normalize_vars();
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
zend_string_release(name);
}
php_session_normalize_vars();
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
#define PS_DELIMITER '|'
PS_SERIALIZER_ENCODE_FUNC(php) /* {{{ */
{
smart_str buf = {0};
php_serialize_data_t var_hash;
PS_ENCODE_VARS;
PHP_VAR_SERIALIZE_INIT(var_hash);
PS_ENCODE_LOOP(
smart_str_appendl(&buf, ZSTR_VAL(key), ZSTR_LEN(key));
if (memchr(ZSTR_VAL(key), PS_DELIMITER, ZSTR_LEN(key))) {
PHP_VAR_SERIALIZE_DESTROY(var_hash);
smart_str_free(&buf);
return NULL;
}
smart_str_appendc(&buf, PS_DELIMITER);
php_var_serialize(&buf, struc, &var_hash);
);
smart_str_0(&buf);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
return buf.s;
}
/* }}} */
PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */
{
const char *p, *q;
const char *endptr = val + vallen;
ptrdiff_t namelen;
zend_string *name;
int retval = SUCCESS;
php_unserialize_data_t var_hash;
zval *current, rv;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
p = val;
while (p < endptr) {
q = p;
while (*q != PS_DELIMITER) {
if (++q >= endptr) goto break_outer_loop;
}
namelen = q - p;
name = zend_string_init(p, namelen, 0);
q++;
current = var_tmp_var(&var_hash);
if (php_var_unserialize(current, (const unsigned char **)&q, (const unsigned char *)endptr, &var_hash)) {
ZVAL_PTR(&rv, current);
php_set_session_var(name, &rv, &var_hash);
} else {
zend_string_release(name);
retval = FAILURE;
goto break_outer_loop;
}
zend_string_release(name);
p = q;
}
break_outer_loop:
php_session_normalize_vars();
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return retval;
}
/* }}} */
#define MAX_SERIALIZERS 32
#define PREDEFINED_SERIALIZERS 3
static ps_serializer ps_serializers[MAX_SERIALIZERS + 1] = {
PS_SERIALIZER_ENTRY(php_serialize),
PS_SERIALIZER_ENTRY(php),
PS_SERIALIZER_ENTRY(php_binary)
};
PHPAPI int php_session_register_serializer(const char *name, zend_string *(*encode)(PS_SERIALIZER_ENCODE_ARGS), int (*decode)(PS_SERIALIZER_DECODE_ARGS)) /* {{{ */
{
int ret = FAILURE;
int i;
for (i = 0; i < MAX_SERIALIZERS; i++) {
if (ps_serializers[i].name == NULL) {
ps_serializers[i].name = name;
ps_serializers[i].encode = encode;
ps_serializers[i].decode = decode;
ps_serializers[i + 1].name = NULL;
ret = SUCCESS;
break;
}
}
return ret;
}
/* }}} */
/* *******************
* Storage Modules *
******************* */
#define MAX_MODULES 32
#define PREDEFINED_MODULES 2
static ps_module *ps_modules[MAX_MODULES + 1] = {
ps_files_ptr,
ps_user_ptr
};
PHPAPI int php_session_register_module(ps_module *ptr) /* {{{ */
{
int ret = FAILURE;
int i;
for (i = 0; i < MAX_MODULES; i++) {
if (!ps_modules[i]) {
ps_modules[i] = ptr;
ret = SUCCESS;
break;
}
}
return ret;
}
/* }}} */
/* Dummy PS module function */
PHPAPI int php_session_validate_sid(PS_VALIDATE_SID_ARGS) {
return SUCCESS;
}
/* Dummy PS module function */
PHPAPI int php_session_update_timestamp(PS_UPDATE_TIMESTAMP_ARGS) {
return SUCCESS;
}
/* ******************
* Cache Limiters *
****************** */
typedef struct {
char *name;
void (*func)(void);
} php_session_cache_limiter_t;
#define CACHE_LIMITER(name) _php_cache_limiter_##name
#define CACHE_LIMITER_FUNC(name) static void CACHE_LIMITER(name)(void)
#define CACHE_LIMITER_ENTRY(name) { #name, CACHE_LIMITER(name) },
#define ADD_HEADER(a) sapi_add_header(a, strlen(a), 1);
#define MAX_STR 512
static char *month_names[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char *week_days[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};
static inline void strcpy_gmt(char *ubuf, time_t *when) /* {{{ */
{
char buf[MAX_STR];
struct tm tm, *res;
int n;
res = php_gmtime_r(when, &tm);
if (!res) {
ubuf[0] = '\0';
return;
}
n = slprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */
week_days[tm.tm_wday], tm.tm_mday,
month_names[tm.tm_mon], tm.tm_year + 1900,
tm.tm_hour, tm.tm_min,
tm.tm_sec);
memcpy(ubuf, buf, n);
ubuf[n] = '\0';
}
/* }}} */
static inline void last_modified(void) /* {{{ */
{
const char *path;
zend_stat_t sb;
char buf[MAX_STR + 1];
path = SG(request_info).path_translated;
if (path) {
if (VCWD_STAT(path, &sb) == -1) {
return;
}
#define LAST_MODIFIED "Last-Modified: "
memcpy(buf, LAST_MODIFIED, sizeof(LAST_MODIFIED) - 1);
strcpy_gmt(buf + sizeof(LAST_MODIFIED) - 1, &sb.st_mtime);
ADD_HEADER(buf);
}
}
/* }}} */
#define EXPIRES "Expires: "
CACHE_LIMITER_FUNC(public) /* {{{ */
{
char buf[MAX_STR + 1];
struct timeval tv;
time_t now;
gettimeofday(&tv, NULL);
now = tv.tv_sec + PS(cache_expire) * 60;
memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now);
ADD_HEADER(buf);
snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
ADD_HEADER(buf);
last_modified();
}
/* }}} */
CACHE_LIMITER_FUNC(private_no_expire) /* {{{ */
{
char buf[MAX_STR + 1];
snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
ADD_HEADER(buf);
last_modified();
}
/* }}} */
CACHE_LIMITER_FUNC(private) /* {{{ */
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
CACHE_LIMITER(private_no_expire)();
}
/* }}} */
CACHE_LIMITER_FUNC(nocache) /* {{{ */
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
/* For HTTP/1.1 conforming clients */
ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate");
/* For HTTP/1.0 conforming clients */
ADD_HEADER("Pragma: no-cache");
}
/* }}} */
static php_session_cache_limiter_t php_session_cache_limiters[] = {
CACHE_LIMITER_ENTRY(public)
CACHE_LIMITER_ENTRY(private)
CACHE_LIMITER_ENTRY(private_no_expire)
CACHE_LIMITER_ENTRY(nocache)
{0}
};
static int php_session_cache_limiter(void) /* {{{ */
{
php_session_cache_limiter_t *lim;
if (PS(cache_limiter)[0] == '\0') return 0;
if (PS(session_status) != php_session_active) return -1;
if (SG(headers_sent)) {
const char *output_start_filename = php_output_get_start_filename();
int output_start_lineno = php_output_get_start_lineno();
php_session_abort();
if (output_start_filename) {
php_error_docref(NULL, E_WARNING, "Cannot send session cache limiter - headers already sent (output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL, E_WARNING, "Cannot send session cache limiter - headers already sent");
}
return -2;
}
for (lim = php_session_cache_limiters; lim->name; lim++) {
if (!strcasecmp(lim->name, PS(cache_limiter))) {
lim->func();
return 0;
}
}
return -1;
}
/* }}} */
/* *********************
* Cookie Management *
********************* */
/*
* Remove already sent session ID cookie.
* It must be directly removed from SG(sapi_header) because sapi_add_header_ex()
* removes all of matching cookie. i.e. It deletes all of Set-Cookie headers.
*/
static void php_session_remove_cookie(void) {
sapi_header_struct *header;
zend_llist *l = &SG(sapi_headers).headers;
zend_llist_element *next;
zend_llist_element *current;
char *session_cookie;
zend_string *e_session_name;
size_t session_cookie_len;
size_t len = sizeof("Set-Cookie")-1;
e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)));
spprintf(&session_cookie, 0, "Set-Cookie: %s=", ZSTR_VAL(e_session_name));
zend_string_free(e_session_name);
session_cookie_len = strlen(session_cookie);
current = l->head;
while (current) {
header = (sapi_header_struct *)(current->data);
next = current->next;
if (header->header_len > len && header->header[len] == ':'
&& !strncmp(header->header, session_cookie, session_cookie_len)) {
if (current->prev) {
current->prev->next = next;
} else {
l->head = next;
}
if (next) {
next->prev = current->prev;
} else {
l->tail = current->prev;
}
sapi_free_header(header);
efree(current);
--l->count;
}
current = next;
}
efree(session_cookie);
}
static int php_session_send_cookie(void) /* {{{ */
{
smart_str ncookie = {0};
zend_string *date_fmt = NULL;
zend_string *e_session_name, *e_id;
if (SG(headers_sent)) {
const char *output_start_filename = php_output_get_start_filename();
int output_start_lineno = php_output_get_start_lineno();
if (output_start_filename) {
php_error_docref(NULL, E_WARNING, "Cannot send session cookie - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno);
} else {
php_error_docref(NULL, E_WARNING, "Cannot send session cookie - headers already sent");
}
return FAILURE;
}
/* URL encode session_name and id because they might be user supplied */
e_session_name = php_url_encode(PS(session_name), strlen(PS(session_name)));
e_id = php_url_encode(ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)));
smart_str_appendl(&ncookie, "Set-Cookie: ", sizeof("Set-Cookie: ")-1);
smart_str_appendl(&ncookie, ZSTR_VAL(e_session_name), ZSTR_LEN(e_session_name));
smart_str_appendc(&ncookie, '=');
smart_str_appendl(&ncookie, ZSTR_VAL(e_id), ZSTR_LEN(e_id));
zend_string_release(e_session_name);
zend_string_release(e_id);
if (PS(cookie_lifetime) > 0) {
struct timeval tv;
time_t t;
gettimeofday(&tv, NULL);
t = tv.tv_sec + PS(cookie_lifetime);
if (t > 0) {
date_fmt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0);
smart_str_appends(&ncookie, COOKIE_EXPIRES);
smart_str_appendl(&ncookie, ZSTR_VAL(date_fmt), ZSTR_LEN(date_fmt));
zend_string_release(date_fmt);
smart_str_appends(&ncookie, COOKIE_MAX_AGE);
smart_str_append_long(&ncookie, PS(cookie_lifetime));
}
}
if (PS(cookie_path)[0]) {
smart_str_appends(&ncookie, COOKIE_PATH);
smart_str_appends(&ncookie, PS(cookie_path));
}
if (PS(cookie_domain)[0]) {
smart_str_appends(&ncookie, COOKIE_DOMAIN);
smart_str_appends(&ncookie, PS(cookie_domain));
}
if (PS(cookie_secure)) {
smart_str_appends(&ncookie, COOKIE_SECURE);
}
if (PS(cookie_httponly)) {
smart_str_appends(&ncookie, COOKIE_HTTPONLY);
}
smart_str_0(&ncookie);
php_session_remove_cookie(); /* remove already sent session ID cookie */
/* 'replace' must be 0 here, else a previous Set-Cookie
header, probably sent with setcookie() will be replaced! */
sapi_add_header_ex(estrndup(ZSTR_VAL(ncookie.s), ZSTR_LEN(ncookie.s)), ZSTR_LEN(ncookie.s), 0, 0);
smart_str_free(&ncookie);
return SUCCESS;
}
/* }}} */
PHPAPI ps_module *_php_find_ps_module(char *name) /* {{{ */
{
ps_module *ret = NULL;
ps_module **mod;
int i;
for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
if (*mod && !strcasecmp(name, (*mod)->s_name)) {
ret = *mod;
break;
}
}
return ret;
}
/* }}} */
PHPAPI const ps_serializer *_php_find_ps_serializer(char *name) /* {{{ */
{
const ps_serializer *ret = NULL;
const ps_serializer *mod;
for (mod = ps_serializers; mod->name; mod++) {
if (!strcasecmp(name, mod->name)) {
ret = mod;
break;
}
}
return ret;
}
/* }}} */
static void ppid2sid(zval *ppid) {
ZVAL_DEREF(ppid);
if (Z_TYPE_P(ppid) == IS_STRING) {
PS(id) = zend_string_init(Z_STRVAL_P(ppid), Z_STRLEN_P(ppid), 0);
PS(send_cookie) = 0;
} else {
PS(id) = NULL;
PS(send_cookie) = 1;
}
}
PHPAPI int php_session_reset_id(void) /* {{{ */
{
int module_number = PS(module_number);
zval *sid, *data, *ppid;
zend_bool apply_trans_sid;
if (!PS(id)) {
php_error_docref(NULL, E_WARNING, "Cannot set session ID - session ID is not initialized");
return FAILURE;
}
if (PS(use_cookies) && PS(send_cookie)) {
php_session_send_cookie();
PS(send_cookie) = 0;
}
/* If the SID constant exists, destroy it. */
/* We must not delete any items in EG(zend_contants) */
/* zend_hash_str_del(EG(zend_constants), "sid", sizeof("sid") - 1); */
sid = zend_get_constant_str("SID", sizeof("SID") - 1);
if (PS(define_sid)) {
smart_str var = {0};
smart_str_appends(&var, PS(session_name));
smart_str_appendc(&var, '=');
smart_str_appends(&var, ZSTR_VAL(PS(id)));
smart_str_0(&var);
if (sid) {
zend_string_release(Z_STR_P(sid));
ZVAL_NEW_STR(sid, var.s);
} else {
REGISTER_STRINGL_CONSTANT("SID", ZSTR_VAL(var.s), ZSTR_LEN(var.s), 0);
smart_str_free(&var);
}
} else {
if (sid) {
zend_string_release(Z_STR_P(sid));
ZVAL_EMPTY_STRING(sid);
} else {
REGISTER_STRINGL_CONSTANT("SID", "", 0, 0);
}
}
/* Apply trans sid if sid cookie is not set */
apply_trans_sid = 0;
if (APPLY_TRANS_SID) {
apply_trans_sid = 1;
if (PS(use_cookies) &&
(data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
ZVAL_DEREF(data);
if (Z_TYPE_P(data) == IS_ARRAY &&
(ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), strlen(PS(session_name))))) {
ZVAL_DEREF(ppid);
apply_trans_sid = 0;
}
}
}
if (apply_trans_sid) {
zend_string *sname;
sname = zend_string_init(PS(session_name), strlen(PS(session_name)), 0);
php_url_scanner_reset_session_var(sname, 1); /* This may fail when session name has changed */
zend_string_release(sname);
php_url_scanner_add_session_var(PS(session_name), strlen(PS(session_name)), ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)), 1);
}
return SUCCESS;
}
/* }}} */
PHPAPI int php_session_start(void) /* {{{ */
{
zval *ppid;
zval *data;
char *p, *value;
size_t lensess;
switch (PS(session_status)) {
case php_session_active:
php_error(E_NOTICE, "A session had already been started - ignoring session_start()");
return FAILURE;
break;
case php_session_disabled:
value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
if (!PS(mod) && value) {
PS(mod) = _php_find_ps_module(value);
if (!PS(mod)) {
php_error_docref(NULL, E_WARNING, "Cannot find save handler '%s' - session startup failed", value);
return FAILURE;
}
}
value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
if (!PS(serializer) && value) {
PS(serializer) = _php_find_ps_serializer(value);
if (!PS(serializer)) {
php_error_docref(NULL, E_WARNING, "Cannot find serialization handler '%s' - session startup failed", value);
return FAILURE;
}
}
PS(session_status) = php_session_none;
/* Fall through */
case php_session_none:
default:
/* Setup internal flags */
PS(define_sid) = !PS(use_only_cookies); /* SID constant is defined when non-cookie ID is used */
PS(send_cookie) = PS(use_cookies) || PS(use_only_cookies);
}
lensess = strlen(PS(session_name));
/*
* Cookies are preferred, because initially cookie and get
* variables will be available.
* URL/POST session ID may be used when use_only_cookies=Off.
* session.use_strice_mode=On prevents session adoption.
* Session based file upload progress uses non-cookie ID.
*/
if (!PS(id)) {
if (PS(use_cookies) && (data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
ZVAL_DEREF(data);
if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
ppid2sid(ppid);
PS(send_cookie) = 0;
PS(define_sid) = 0;
}
}
/* Initilize session ID from non cookie values */
if (!PS(use_only_cookies)) {
if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_GET", sizeof("_GET") - 1))) {
ZVAL_DEREF(data);
if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
ppid2sid(ppid);
}
}
if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_POST", sizeof("_POST") - 1))) {
ZVAL_DEREF(data);
if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
ppid2sid(ppid);
}
}
/* Check the REQUEST_URI symbol for a string of the form
* '<session-name>=<session-id>' to allow URLs of the form
* http://yoursite/<session-name>=<session-id>/script.php */
if (!PS(id) && zend_is_auto_global_str("_SERVER", sizeof("_SERVER") - 1) == SUCCESS &&
(data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "REQUEST_URI", sizeof("REQUEST_URI") - 1)) &&
Z_TYPE_P(data) == IS_STRING &&
(p = strstr(Z_STRVAL_P(data), PS(session_name))) &&
p[lensess] == '='
) {
char *q;
p += lensess + 1;
if ((q = strpbrk(p, "/?\\"))) {
PS(id) = zend_string_init(p, q - p, 0);
}
}
/* Check whether the current request was referred to by
* an external site which invalidates the previously found id. */
if (PS(id) && PS(extern_referer_chk)[0] != '\0' &&
!Z_ISUNDEF(PG(http_globals)[TRACK_VARS_SERVER]) &&
(data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER") - 1)) &&
Z_TYPE_P(data) == IS_STRING &&
Z_STRLEN_P(data) != 0 &&
strstr(Z_STRVAL_P(data), PS(extern_referer_chk)) == NULL
) {
zend_string_release(PS(id));
PS(id) = NULL;
}
}
}
/* Finally check session id for dangerous characters
* Security note: session id may be embedded in HTML pages.*/
if (PS(id) && strpbrk(ZSTR_VAL(PS(id)), "\r\n\t <>'\"\\")) {
zend_string_release(PS(id));
PS(id) = NULL;
}
if (php_session_initialize() == FAILURE
|| php_session_cache_limiter() == -2) {
PS(session_status) = php_session_none;
if (PS(id)) {
zend_string_release(PS(id));
PS(id) = NULL;
}
return FAILURE;
}
return SUCCESS;
}
/* }}} */
PHPAPI int php_session_flush(int write) /* {{{ */
{
if (PS(session_status) == php_session_active) {
php_session_save_current_state(write);
PS(session_status) = php_session_none;
return SUCCESS;
}
return FAILURE;
}
/* }}} */
static int php_session_abort(void) /* {{{ */
{
if (PS(session_status) == php_session_active) {
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data));
}
PS(session_status) = php_session_none;
return SUCCESS;
}
return FAILURE;
}
/* }}} */
static int php_session_reset(void) /* {{{ */
{
if (PS(session_status) == php_session_active
&& php_session_initialize() == SUCCESS) {
return SUCCESS;
}
return FAILURE;
}
/* }}} */
/* This API is not used by any PHP modules including session currently.
session_adapt_url() may be used to set Session ID to target url without
starting "URL-Rewriter" output handler. */
PHPAPI void session_adapt_url(const char *url, size_t urllen, char **new, size_t *newlen) /* {{{ */
{
if (APPLY_TRANS_SID && (PS(session_status) == php_session_active)) {
*new = php_url_scanner_adapt_single_url(url, urllen, PS(session_name), ZSTR_VAL(PS(id)), newlen, 1);
}
}
/* }}} */
/* ********************************
* Userspace exported functions *
******************************** */
/* {{{ proto bool session_set_cookie_params(int lifetime [, string path [, string domain [, bool secure[, bool httponly]]]])
Set session cookie parameters */
static PHP_FUNCTION(session_set_cookie_params)
{
zval *lifetime;
zend_string *path = NULL, *domain = NULL;
int argc = ZEND_NUM_ARGS();
zend_bool secure = 0, httponly = 0;
zend_string *ini_name;
if (!PS(use_cookies) ||
zend_parse_parameters(argc, "z|SSbb", &lifetime, &path, &domain, &secure, &httponly) == FAILURE) {
return;
}
if (PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change session cookie parameters when session is active");
RETURN_FALSE;
}
if (SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change session cookie parameters when headers already sent");
RETURN_FALSE;
}
convert_to_string_ex(lifetime);
ini_name = zend_string_init("session.cookie_lifetime", sizeof("session.cookie_lifetime") - 1, 0);
if (zend_alter_ini_entry(ini_name, Z_STR_P(lifetime), PHP_INI_USER, PHP_INI_STAGE_RUNTIME) == FAILURE) {
zend_string_release(ini_name);
RETURN_FALSE;
}
zend_string_release(ini_name);
if (path) {
ini_name = zend_string_init("session.cookie_path", sizeof("session.cookie_path") - 1, 0);
if (zend_alter_ini_entry(ini_name, path, PHP_INI_USER, PHP_INI_STAGE_RUNTIME) == FAILURE) {
zend_string_release(ini_name);
RETURN_FALSE;
}
zend_string_release(ini_name);
}
if (domain) {
ini_name = zend_string_init("session.cookie_domain", sizeof("session.cookie_domain") - 1, 0);
if (zend_alter_ini_entry(ini_name, domain, PHP_INI_USER, PHP_INI_STAGE_RUNTIME) == FAILURE) {
zend_string_release(ini_name);
RETURN_FALSE;
}
zend_string_release(ini_name);
}
if (argc > 3) {
ini_name = zend_string_init("session.cookie_secure", sizeof("session.cookie_secure") - 1, 0);
if (zend_alter_ini_entry_chars(ini_name, secure ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME) == FAILURE) {
zend_string_release(ini_name);
RETURN_FALSE;
}
zend_string_release(ini_name);
}
if (argc > 4) {
ini_name = zend_string_init("session.cookie_httponly", sizeof("session.cookie_httponly") - 1, 0);
if (zend_alter_ini_entry_chars(ini_name, httponly ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME) == FAILURE) {
zend_string_release(ini_name);
RETURN_FALSE;
}
zend_string_release(ini_name);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto array session_get_cookie_params(void)
Return the session cookie parameters */
static PHP_FUNCTION(session_get_cookie_params)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_assoc_long(return_value, "lifetime", PS(cookie_lifetime));
add_assoc_string(return_value, "path", PS(cookie_path));
add_assoc_string(return_value, "domain", PS(cookie_domain));
add_assoc_bool(return_value, "secure", PS(cookie_secure));
add_assoc_bool(return_value, "httponly", PS(cookie_httponly));
}
/* }}} */
/* {{{ proto string session_name([string newname])
Return the current session name. If newname is given, the session name is replaced with newname */
static PHP_FUNCTION(session_name)
{
zend_string *name = NULL;
zend_string *ini_name;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &name) == FAILURE) {
return;
}
if (name && PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change session name when session is active");
RETURN_FALSE;
}
if (name && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change session name when headers already sent");
RETURN_FALSE;
}
RETVAL_STRING(PS(session_name));
if (name) {
ini_name = zend_string_init("session.name", sizeof("session.name") - 1, 0);
zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release(ini_name);
}
}
/* }}} */
/* {{{ proto string session_module_name([string newname])
Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname */
static PHP_FUNCTION(session_module_name)
{
zend_string *name = NULL;
zend_string *ini_name;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &name) == FAILURE) {
return;
}
if (name && PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change save handler module when session is active");
RETURN_FALSE;
}
if (name && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change save handler module when headers already sent");
RETURN_FALSE;
}
/* Set return_value to current module name */
if (PS(mod) && PS(mod)->s_name) {
RETVAL_STRING(PS(mod)->s_name);
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (!_php_find_ps_module(ZSTR_VAL(name))) {
php_error_docref(NULL, E_WARNING, "Cannot find named PHP session module (%s)", ZSTR_VAL(name));
zval_dtor(return_value);
RETURN_FALSE;
}
if (PS(mod_data) || PS(mod_user_implemented)) {
PS(mod)->s_close(&PS(mod_data));
}
PS(mod_data) = NULL;
ini_name = zend_string_init("session.save_handler", sizeof("session.save_handler") - 1, 0);
zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release(ini_name);
}
}
/* }}} */
/* {{{ proto bool session_set_save_handler(string open, string close, string read, string write, string destroy, string gc, string create_sid)
Sets user-level functions */
static PHP_FUNCTION(session_set_save_handler)
{
zval *args = NULL;
int i, num_args, argc = ZEND_NUM_ARGS();
zend_string *ini_name, *ini_val;
if (PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change save handler when session is active");
RETURN_FALSE;
}
if (SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change save handler when headers already sent");
RETURN_FALSE;
}
if (argc > 0 && argc <= 2) {
zval *obj = NULL;
zend_string *func_name;
zend_function *current_mptr;
zend_bool register_shutdown = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|b", &obj, php_session_iface_entry, ®ister_shutdown) == FAILURE) {
RETURN_FALSE;
}
/* For compatibility reason, implemeted interface is not checked */
/* Find implemented methods - SessionHandlerInterface */
i = 0;
ZEND_HASH_FOREACH_STR_KEY(&php_session_iface_entry->function_table, func_name) {
if ((current_mptr = zend_hash_find_ptr(&Z_OBJCE_P(obj)->function_table, func_name))) {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
array_init_size(&PS(mod_user_names).names[i], 2);
Z_ADDREF_P(obj);
add_next_index_zval(&PS(mod_user_names).names[i], obj);
add_next_index_str(&PS(mod_user_names).names[i], zend_string_copy(func_name));
} else {
php_error_docref(NULL, E_ERROR, "Session handler's function table is corrupt");
RETURN_FALSE;
}
++i;
} ZEND_HASH_FOREACH_END();
/* Find implemented methods - SessionIdInterface (optional) */
ZEND_HASH_FOREACH_STR_KEY(&php_session_id_iface_entry->function_table, func_name) {
if ((current_mptr = zend_hash_find_ptr(&Z_OBJCE_P(obj)->function_table, func_name))) {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
array_init_size(&PS(mod_user_names).names[i], 2);
Z_ADDREF_P(obj);
add_next_index_zval(&PS(mod_user_names).names[i], obj);
add_next_index_str(&PS(mod_user_names).names[i], zend_string_copy(func_name));
} else {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
ZVAL_UNDEF(&PS(mod_user_names).names[i]);
}
}
++i;
} ZEND_HASH_FOREACH_END();
/* Find implemented methods - SessionUpdateTimestampInterface (optional) */
ZEND_HASH_FOREACH_STR_KEY(&php_session_update_timestamp_iface_entry->function_table, func_name) {
if ((current_mptr = zend_hash_find_ptr(&Z_OBJCE_P(obj)->function_table, func_name))) {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
array_init_size(&PS(mod_user_names).names[i], 2);
Z_ADDREF_P(obj);
add_next_index_zval(&PS(mod_user_names).names[i], obj);
add_next_index_str(&PS(mod_user_names).names[i], zend_string_copy(func_name));
} else {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
ZVAL_UNDEF(&PS(mod_user_names).names[i]);
}
}
++i;
} ZEND_HASH_FOREACH_END();
if (register_shutdown) {
/* create shutdown function */
php_shutdown_function_entry shutdown_function_entry;
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval *) safe_emalloc(sizeof(zval), 1, 0);
ZVAL_STRING(&shutdown_function_entry.arguments[0], "session_register_shutdown");
/* add shutdown function, removing the old one if it exists */
if (!register_user_shutdown_function("session_shutdown", sizeof("session_shutdown") - 1, &shutdown_function_entry)) {
zval_ptr_dtor(&shutdown_function_entry.arguments[0]);
efree(shutdown_function_entry.arguments);
php_error_docref(NULL, E_WARNING, "Unable to register session shutdown function");
RETURN_FALSE;
}
} else {
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") - 1);
}
if (PS(mod) && PS(session_status) != php_session_active && PS(mod) != &ps_mod_user) {
ini_name = zend_string_init("session.save_handler", sizeof("session.save_handler") - 1, 0);
ini_val = zend_string_init("user", sizeof("user") - 1, 0);
PS(set_handler) = 1;
zend_alter_ini_entry(ini_name, ini_val, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
PS(set_handler) = 0;
zend_string_release(ini_val);
zend_string_release(ini_name);
}
RETURN_TRUE;
}
/* Set procedural save handler functions */
if (argc < 6 || PS_NUM_APIS < argc) {
WRONG_PARAM_COUNT;
}
if (zend_parse_parameters(argc, "+", &args, &num_args) == FAILURE) {
return;
}
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") - 1);
/* At this point argc can only be between 6 and PS_NUM_APIS */
for (i = 0; i < argc; i++) {
if (!zend_is_callable(&args[i], 0, NULL)) {
zend_string *name = zend_get_callable_name(&args[i]);
php_error_docref(NULL, E_WARNING, "Argument %d is not a valid callback", i+1);
zend_string_release(name);
RETURN_FALSE;
}
}
if (PS(mod) && PS(mod) != &ps_mod_user) {
ini_name = zend_string_init("session.save_handler", sizeof("session.save_handler") - 1, 0);
ini_val = zend_string_init("user", sizeof("user") - 1, 0);
PS(set_handler) = 1;
zend_alter_ini_entry(ini_name, ini_val, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
PS(set_handler) = 0;
zend_string_release(ini_val);
zend_string_release(ini_name);
}
for (i = 0; i < argc; i++) {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
ZVAL_COPY(&PS(mod_user_names).names[i], &args[i]);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string session_save_path([string newname])
Return the current save path passed to module_name. If newname is given, the save path is replaced with newname */
static PHP_FUNCTION(session_save_path)
{
zend_string *name = NULL;
zend_string *ini_name;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &name) == FAILURE) {
return;
}
if (name && PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change save path when session is active");
RETURN_FALSE;
}
if (name && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change save path when headers already sent");
RETURN_FALSE;
}
RETVAL_STRING(PS(save_path));
if (name) {
if (memchr(ZSTR_VAL(name), '\0', ZSTR_LEN(name)) != NULL) {
php_error_docref(NULL, E_WARNING, "The save_path cannot contain NULL characters");
zval_dtor(return_value);
RETURN_FALSE;
}
ini_name = zend_string_init("session.save_path", sizeof("session.save_path") - 1, 0);
zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release(ini_name);
}
}
/* }}} */
/* {{{ proto string session_id([string newid])
Return the current session id. If newid is given, the session id is replaced with newid */
static PHP_FUNCTION(session_id)
{
zend_string *name = NULL;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "|S", &name) == FAILURE) {
return;
}
if (name && PS(use_cookies) && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change session id when headers already sent");
RETURN_FALSE;
}
if (PS(id)) {
/* keep compatibility for "\0" characters ???
* see: ext/session/tests/session_id_error3.phpt */
size_t len = strlen(ZSTR_VAL(PS(id)));
if (UNEXPECTED(len != ZSTR_LEN(PS(id)))) {
RETVAL_NEW_STR(zend_string_init(ZSTR_VAL(PS(id)), len, 0));
} else {
RETVAL_STR_COPY(PS(id));
}
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (PS(id)) {
zend_string_release(PS(id));
}
PS(id) = zend_string_copy(name);
}
}
/* }}} */
/* {{{ proto bool session_regenerate_id([bool delete_old_session])
Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. */
static PHP_FUNCTION(session_regenerate_id)
{
zend_bool del_ses = 0;
zend_string *data;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &del_ses) == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot regenerate session id - session is not active");
RETURN_FALSE;
}
if (SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot regenerate session id - headers already sent");
RETURN_FALSE;
}
/* Process old session data */
if (del_ses) {
if (PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
PS(mod)->s_close(&PS(mod_data));
PS(session_status) = php_session_none;
php_error_docref(NULL, E_WARNING, "Session object destruction failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
RETURN_FALSE;
}
} else {
int ret;
data = php_session_encode();
if (data) {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), data, PS(gc_maxlifetime));
zend_string_release(data);
} else {
ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
}
if (ret == FAILURE) {
PS(mod)->s_close(&PS(mod_data));
PS(session_status) = php_session_none;
php_error_docref(NULL, E_WARNING, "Session write failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
RETURN_FALSE;
}
}
PS(mod)->s_close(&PS(mod_data));
/* New session data */
if (PS(session_vars)) {
zend_string_release(PS(session_vars));
PS(session_vars) = NULL;
}
zend_string_release(PS(id));
PS(id) = NULL;
if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE) {
PS(session_status) = php_session_none;
zend_throw_error(NULL, "Failed to open session: %s (path: %s)", PS(mod)->s_name, PS(save_path));
RETURN_FALSE;
}
PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
if (!PS(id)) {
PS(session_status) = php_session_none;
zend_throw_error(NULL, "Failed to create new session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
RETURN_FALSE;
}
if (PS(use_strict_mode) && PS(mod)->s_validate_sid &&
PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == FAILURE) {
zend_string_release(PS(id));
PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
if (!PS(id)) {
PS(mod)->s_close(&PS(mod_data));
PS(session_status) = php_session_none;
zend_throw_error(NULL, "Failed to create session ID by collision: %s (path: %s)", PS(mod)->s_name, PS(save_path));
RETURN_FALSE;
}
}
/* Read is required to make new session data at this point. */
if (PS(mod)->s_read(&PS(mod_data), PS(id), &data, PS(gc_maxlifetime)) == FAILURE) {
PS(mod)->s_close(&PS(mod_data));
PS(session_status) = php_session_none;
zend_throw_error(NULL, "Failed to create(read) session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
RETURN_FALSE;
}
if (data) {
zend_string_release(data);
}
if (PS(use_cookies)) {
PS(send_cookie) = 1;
}
if (php_session_reset_id() == FAILURE) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto string session_create_id([string prefix])
Generate new session ID. Intended for user save handlers. */
/* This is not used yet */
static PHP_FUNCTION(session_create_id)
{
zend_string *prefix = NULL, *new_id;
smart_str id = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &prefix) == FAILURE) {
return;
}
if (prefix && ZSTR_LEN(prefix)) {
if (php_session_valid_key(ZSTR_VAL(prefix)) == FAILURE) {
/* E_ERROR raised for security reason. */
php_error_docref(NULL, E_WARNING, "Prefix cannot contain special characters. Only aphanumeric, ',', '-' are allowed");
RETURN_FALSE;
} else {
smart_str_append(&id, prefix);
}
}
if (!PS(in_save_handler) && PS(session_status) == php_session_active) {
int limit = 3;
while (limit--) {
new_id = PS(mod)->s_create_sid(&PS(mod_data));
if (!PS(mod)->s_validate_sid) {
break;
} else {
/* Detect collision and retry */
if (PS(mod)->s_validate_sid(&PS(mod_data), new_id) == FAILURE) {
zend_string_release(new_id);
continue;
}
break;
}
}
} else {
new_id = php_session_create_id(NULL);
}
if (new_id) {
smart_str_append(&id, new_id);
zend_string_release(new_id);
} else {
smart_str_free(&id);
php_error_docref(NULL, E_WARNING, "Failed to create new ID");
RETURN_FALSE;
}
smart_str_0(&id);
RETVAL_NEW_STR(id.s);
}
/* }}} */
/* {{{ proto string session_cache_limiter([string new_cache_limiter])
Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter */
static PHP_FUNCTION(session_cache_limiter)
{
zend_string *limiter = NULL;
zend_string *ini_name;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &limiter) == FAILURE) {
return;
}
if (limiter && PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change cache limiter when session is active");
RETURN_FALSE;
}
if (limiter && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change cache limiter when headers already sent");
RETURN_FALSE;
}
RETVAL_STRING(PS(cache_limiter));
if (limiter) {
ini_name = zend_string_init("session.cache_limiter", sizeof("session.cache_limiter") - 1, 0);
zend_alter_ini_entry(ini_name, limiter, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
zend_string_release(ini_name);
}
}
/* }}} */
/* {{{ proto int session_cache_expire([int new_cache_expire])
Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire */
static PHP_FUNCTION(session_cache_expire)
{
zval *expires = NULL;
zend_string *ini_name;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|z", &expires) == FAILURE) {
return;
}
if (expires && PS(session_status) == php_session_active) {
php_error_docref(NULL, E_WARNING, "Cannot change cache expire when session is active");
RETURN_LONG(PS(cache_expire));
}
if (expires && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot change cache expire when headers already sent");
RETURN_FALSE;
}
RETVAL_LONG(PS(cache_expire));
if (expires) {
convert_to_string_ex(expires);
ini_name = zend_string_init("session.cache_expire", sizeof("session.cache_expire") - 1, 0);
zend_alter_ini_entry(ini_name, Z_STR_P(expires), ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
zend_string_release(ini_name);
}
}
/* }}} */
/* {{{ proto string session_encode(void)
Serializes the current setup and returns the serialized representation */
static PHP_FUNCTION(session_encode)
{
zend_string *enc;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
enc = php_session_encode();
if (enc == NULL) {
RETURN_FALSE;
}
RETURN_STR(enc);
}
/* }}} */
/* {{{ proto bool session_decode(string data)
Deserializes data and reinitializes the variables */
static PHP_FUNCTION(session_decode)
{
zend_string *str = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
php_error_docref(NULL, E_WARNING, "Session is not active. You cannot decode session data");
RETURN_FALSE;
}
if (php_session_decode(str) == FAILURE) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
static int php_session_start_set_ini(zend_string *varname, zend_string *new_value) {
int ret;
smart_str buf ={0};
smart_str_appends(&buf, "session");
smart_str_appendc(&buf, '.');
smart_str_append(&buf, varname);
smart_str_0(&buf);
ret = zend_alter_ini_entry_ex(buf.s, new_value, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0);
smart_str_free(&buf);
return ret;
}
/* {{{ proto bool session_start([array options])
+ Begin session */
static PHP_FUNCTION(session_start)
{
zval *options = NULL;
zval *value;
zend_ulong num_idx;
zend_string *str_idx;
zend_long read_and_close = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a", &options) == FAILURE) {
RETURN_FALSE;
}
if (PS(session_status) == php_session_active) {
php_error_docref(NULL, E_NOTICE, "A session had already been started - ignoring");
RETURN_TRUE;
}
/*
* TODO: To prevent unusable session with trans sid, actual output started status is
* required. i.e. There shouldn't be any outputs in output buffer, otherwise session
* module is unable to rewrite output.
*/
if (PS(use_cookies) && SG(headers_sent)) {
php_error_docref(NULL, E_WARNING, "Cannot start session when headers already sent");
RETURN_FALSE;
}
/* set options */
if (options) {
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(options), num_idx, str_idx, value) {
if (str_idx) {
switch(Z_TYPE_P(value)) {
case IS_STRING:
case IS_TRUE:
case IS_FALSE:
case IS_LONG:
if (zend_string_equals_literal(str_idx, "read_and_close")) {
read_and_close = zval_get_long(value);
} else {
zend_string *val = zval_get_string(value);
if (php_session_start_set_ini(str_idx, val) == FAILURE) {
php_error_docref(NULL, E_WARNING, "Setting option '%s' failed", ZSTR_VAL(str_idx));
}
zend_string_release(val);
}
break;
default:
php_error_docref(NULL, E_WARNING, "Option(%s) value must be string, boolean or long", ZSTR_VAL(str_idx));
break;
}
}
(void) num_idx;
} ZEND_HASH_FOREACH_END();
}
php_session_start();
if (PS(session_status) != php_session_active) {
IF_SESSION_VARS() {
zval *sess_var = Z_REFVAL(PS(http_session_vars));
SEPARATE_ARRAY(sess_var);
/* Clean $_SESSION. */
zend_hash_clean(Z_ARRVAL_P(sess_var));
}
RETURN_FALSE;
}
if (read_and_close) {
php_session_flush(0);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool session_destroy(void)
Destroy the current session and all data associated with it */
static PHP_FUNCTION(session_destroy)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(php_session_destroy() == SUCCESS);
}
/* }}} */
/* {{{ proto bool session_unset(void)
Unset all registered variables */
static PHP_FUNCTION(session_unset)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
RETURN_FALSE;
}
IF_SESSION_VARS() {
zval *sess_var = Z_REFVAL(PS(http_session_vars));
SEPARATE_ARRAY(sess_var);
/* Clean $_SESSION. */
zend_hash_clean(Z_ARRVAL_P(sess_var));
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int session_gc(void)
Perform GC and return number of deleted sessions */
static PHP_FUNCTION(session_gc)
{
zend_long num;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
php_error_docref(NULL, E_WARNING, "Session is not active");
RETURN_FALSE;
}
num = php_session_gc(1);
if (num < 0) {
RETURN_FALSE;
}
RETURN_LONG(num);
}
/* }}} */
/* {{{ proto bool session_write_close(void)
Write session data and end session */
static PHP_FUNCTION(session_write_close)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
RETURN_FALSE;
}
php_session_flush(1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool session_abort(void)
Abort session and end session. Session data will not be written */
static PHP_FUNCTION(session_abort)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
RETURN_FALSE;
}
php_session_abort();
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool session_reset(void)
Reset session data from saved session data */
static PHP_FUNCTION(session_reset)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (PS(session_status) != php_session_active) {
RETURN_FALSE;
}
php_session_reset();
RETURN_TRUE;
}
/* }}} */
/* {{{ proto int session_status(void)
Returns the current session status */
static PHP_FUNCTION(session_status)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(PS(session_status));
}
/* }}} */
/* {{{ proto void session_register_shutdown(void)
Registers session_write_close() as a shutdown function */
static PHP_FUNCTION(session_register_shutdown)
{
php_shutdown_function_entry shutdown_function_entry;
/* This function is registered itself as a shutdown function by
* session_set_save_handler($obj). The reason we now register another
* shutdown function is in case the user registered their own shutdown
* function after calling session_set_save_handler(), which expects
* the session still to be available.
*/
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval *) safe_emalloc(sizeof(zval), 1, 0);
ZVAL_STRING(&shutdown_function_entry.arguments[0], "session_write_close");
if (!append_user_shutdown_function(shutdown_function_entry)) {
zval_ptr_dtor(&shutdown_function_entry.arguments[0]);
efree(shutdown_function_entry.arguments);
/* Unable to register shutdown function, presumably because of lack
* of memory, so flush the session now. It would be done in rshutdown
* anyway but the handler will have had it's dtor called by then.
* If the user does have a later shutdown function which needs the
* session then tough luck.
*/
php_session_flush(1);
php_error_docref(NULL, E_WARNING, "Unable to register session flush function");
}
}
/* }}} */
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_name, 0, 0, 0)
ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_module_name, 0, 0, 0)
ZEND_ARG_INFO(0, module)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_save_path, 0, 0, 0)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_id, 0, 0, 0)
ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_create_id, 0, 0, 0)
ZEND_ARG_INFO(0, prefix)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_regenerate_id, 0, 0, 0)
ZEND_ARG_INFO(0, delete_old_session)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_decode, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_void, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_set_save_handler, 0, 0, 1)
ZEND_ARG_INFO(0, open)
ZEND_ARG_INFO(0, close)
ZEND_ARG_INFO(0, read)
ZEND_ARG_INFO(0, write)
ZEND_ARG_INFO(0, destroy)
ZEND_ARG_INFO(0, gc)
ZEND_ARG_INFO(0, create_sid)
ZEND_ARG_INFO(0, validate_sid)
ZEND_ARG_INFO(0, update_timestamp)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_cache_limiter, 0, 0, 0)
ZEND_ARG_INFO(0, cache_limiter)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_cache_expire, 0, 0, 0)
ZEND_ARG_INFO(0, new_cache_expire)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_set_cookie_params, 0, 0, 1)
ZEND_ARG_INFO(0, lifetime)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, domain)
ZEND_ARG_INFO(0, secure)
ZEND_ARG_INFO(0, httponly)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_open, 0)
ZEND_ARG_INFO(0, save_path)
ZEND_ARG_INFO(0, session_name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_close, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_read, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_write, 0)
ZEND_ARG_INFO(0, key)
ZEND_ARG_INFO(0, val)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_destroy, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_gc, 0)
ZEND_ARG_INFO(0, maxlifetime)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_create_sid, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_validateId, 0)
ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_session_class_updateTimestamp, 0)
ZEND_ARG_INFO(0, key)
ZEND_ARG_INFO(0, val)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_session_start, 0, 0, 0)
ZEND_ARG_INFO(0, options) /* array */
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ session_functions[]
*/
static const zend_function_entry session_functions[] = {
PHP_FE(session_name, arginfo_session_name)
PHP_FE(session_module_name, arginfo_session_module_name)
PHP_FE(session_save_path, arginfo_session_save_path)
PHP_FE(session_id, arginfo_session_id)
PHP_FE(session_create_id, arginfo_session_create_id)
PHP_FE(session_regenerate_id, arginfo_session_regenerate_id)
PHP_FE(session_decode, arginfo_session_decode)
PHP_FE(session_encode, arginfo_session_void)
PHP_FE(session_start, arginfo_session_start)
PHP_FE(session_destroy, arginfo_session_void)
PHP_FE(session_unset, arginfo_session_void)
PHP_FE(session_gc, arginfo_session_void)
PHP_FE(session_set_save_handler, arginfo_session_set_save_handler)
PHP_FE(session_cache_limiter, arginfo_session_cache_limiter)
PHP_FE(session_cache_expire, arginfo_session_cache_expire)
PHP_FE(session_set_cookie_params, arginfo_session_set_cookie_params)
PHP_FE(session_get_cookie_params, arginfo_session_void)
PHP_FE(session_write_close, arginfo_session_void)
PHP_FE(session_abort, arginfo_session_void)
PHP_FE(session_reset, arginfo_session_void)
PHP_FE(session_status, arginfo_session_void)
PHP_FE(session_register_shutdown, arginfo_session_void)
PHP_FALIAS(session_commit, session_write_close, arginfo_session_void)
PHP_FE_END
};
/* }}} */
/* {{{ SessionHandlerInterface functions[]
*/
static const zend_function_entry php_session_iface_functions[] = {
PHP_ABSTRACT_ME(SessionHandlerInterface, open, arginfo_session_class_open)
PHP_ABSTRACT_ME(SessionHandlerInterface, close, arginfo_session_class_close)
PHP_ABSTRACT_ME(SessionHandlerInterface, read, arginfo_session_class_read)
PHP_ABSTRACT_ME(SessionHandlerInterface, write, arginfo_session_class_write)
PHP_ABSTRACT_ME(SessionHandlerInterface, destroy, arginfo_session_class_destroy)
PHP_ABSTRACT_ME(SessionHandlerInterface, gc, arginfo_session_class_gc)
PHP_FE_END
};
/* }}} */
/* {{{ SessionIdInterface functions[]
*/
static const zend_function_entry php_session_id_iface_functions[] = {
PHP_ABSTRACT_ME(SessionIdInterface, create_sid, arginfo_session_class_create_sid)
PHP_FE_END
};
/* }}} */
/* {{{ SessionUpdateTimestampHandler functions[]
*/
static const zend_function_entry php_session_update_timestamp_iface_functions[] = {
PHP_ABSTRACT_ME(SessionUpdateTimestampHandlerInterface, validateId, arginfo_session_class_validateId)
PHP_ABSTRACT_ME(SessionUpdateTimestampHandlerInterface, updateTimestamp, arginfo_session_class_updateTimestamp)
PHP_FE_END
};
/* }}} */
/* {{{ SessionHandler functions[]
*/
static const zend_function_entry php_session_class_functions[] = {
PHP_ME(SessionHandler, open, arginfo_session_class_open, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, close, arginfo_session_class_close, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, read, arginfo_session_class_read, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, write, arginfo_session_class_write, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, destroy, arginfo_session_class_destroy, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, gc, arginfo_session_class_gc, ZEND_ACC_PUBLIC)
PHP_ME(SessionHandler, create_sid, arginfo_session_class_create_sid, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/* ********************************
* Module Setup and Destruction *
******************************** */
static int php_rinit_session(zend_bool auto_start) /* {{{ */
{
php_rinit_session_globals();
if (PS(mod) == NULL) {
char *value;
value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
if (value) {
PS(mod) = _php_find_ps_module(value);
}
}
if (PS(serializer) == NULL) {
char *value;
value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
if (value) {
PS(serializer) = _php_find_ps_serializer(value);
}
}
if (PS(mod) == NULL || PS(serializer) == NULL) {
/* current status is unusable */
PS(session_status) = php_session_disabled;
return SUCCESS;
}
if (auto_start) {
php_session_start();
}
return SUCCESS;
} /* }}} */
static PHP_RINIT_FUNCTION(session) /* {{{ */
{
return php_rinit_session(PS(auto_start));
}
/* }}} */
static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */
{
int i;
if (PS(session_status) == php_session_active) {
zend_try {
php_session_flush(1);
} zend_end_try();
}
php_rshutdown_session_globals();
/* this should NOT be done in php_rshutdown_session_globals() */
for (i = 0; i < PS_NUM_APIS; i++) {
if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
ZVAL_UNDEF(&PS(mod_user_names).names[i]);
}
}
return SUCCESS;
}
/* }}} */
static PHP_GINIT_FUNCTION(ps) /* {{{ */
{
int i;
#if defined(COMPILE_DL_SESSION) && defined(ZTS)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
ps_globals->save_path = NULL;
ps_globals->session_name = NULL;
ps_globals->id = NULL;
ps_globals->mod = NULL;
ps_globals->serializer = NULL;
ps_globals->mod_data = NULL;
ps_globals->session_status = php_session_none;
ps_globals->default_mod = NULL;
ps_globals->mod_user_implemented = 0;
ps_globals->mod_user_is_open = 0;
ps_globals->session_vars = NULL;
ps_globals->set_handler = 0;
for (i = 0; i < PS_NUM_APIS; i++) {
ZVAL_UNDEF(&ps_globals->mod_user_names.names[i]);
}
ZVAL_UNDEF(&ps_globals->http_session_vars);
}
/* }}} */
static PHP_MINIT_FUNCTION(session) /* {{{ */
{
zend_class_entry ce;
zend_register_auto_global(zend_string_init("_SESSION", sizeof("_SESSION") - 1, 1), 0, NULL);
my_module_number = module_number;
PS(module_number) = module_number;
PS(session_status) = php_session_none;
REGISTER_INI_ENTRIES();
#ifdef HAVE_LIBMM
PHP_MINIT(ps_mm) (INIT_FUNC_ARGS_PASSTHRU);
#endif
php_session_rfc1867_orig_callback = php_rfc1867_callback;
php_rfc1867_callback = php_session_rfc1867_callback;
/* Register interfaces */
INIT_CLASS_ENTRY(ce, PS_IFACE_NAME, php_session_iface_functions);
php_session_iface_entry = zend_register_internal_class(&ce);
php_session_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
INIT_CLASS_ENTRY(ce, PS_SID_IFACE_NAME, php_session_id_iface_functions);
php_session_id_iface_entry = zend_register_internal_class(&ce);
php_session_id_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
INIT_CLASS_ENTRY(ce, PS_UPDATE_TIMESTAMP_IFACE_NAME, php_session_update_timestamp_iface_functions);
php_session_update_timestamp_iface_entry = zend_register_internal_class(&ce);
php_session_update_timestamp_iface_entry->ce_flags |= ZEND_ACC_INTERFACE;
/* Register base class */
INIT_CLASS_ENTRY(ce, PS_CLASS_NAME, php_session_class_functions);
php_session_class_entry = zend_register_internal_class(&ce);
zend_class_implements(php_session_class_entry, 1, php_session_iface_entry);
zend_class_implements(php_session_class_entry, 1, php_session_id_iface_entry);
REGISTER_LONG_CONSTANT("PHP_SESSION_DISABLED", php_session_disabled, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_SESSION_NONE", php_session_none, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("PHP_SESSION_ACTIVE", php_session_active, CONST_CS | CONST_PERSISTENT);
return SUCCESS;
}
/* }}} */
static PHP_MSHUTDOWN_FUNCTION(session) /* {{{ */
{
UNREGISTER_INI_ENTRIES();
#ifdef HAVE_LIBMM
PHP_MSHUTDOWN(ps_mm) (SHUTDOWN_FUNC_ARGS_PASSTHRU);
#endif
/* reset rfc1867 callbacks */
php_session_rfc1867_orig_callback = NULL;
if (php_rfc1867_callback == php_session_rfc1867_callback) {
php_rfc1867_callback = NULL;
}
ps_serializers[PREDEFINED_SERIALIZERS].name = NULL;
memset(&ps_modules[PREDEFINED_MODULES], 0, (MAX_MODULES-PREDEFINED_MODULES)*sizeof(ps_module *));
return SUCCESS;
}
/* }}} */
static PHP_MINFO_FUNCTION(session) /* {{{ */
{
ps_module **mod;
ps_serializer *ser;
smart_str save_handlers = {0};
smart_str ser_handlers = {0};
int i;
/* Get save handlers */
for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
if (*mod && (*mod)->s_name) {
smart_str_appends(&save_handlers, (*mod)->s_name);
smart_str_appendc(&save_handlers, ' ');
}
}
/* Get serializer handlers */
for (i = 0, ser = ps_serializers; i < MAX_SERIALIZERS; i++, ser++) {
if (ser && ser->name) {
smart_str_appends(&ser_handlers, ser->name);
smart_str_appendc(&ser_handlers, ' ');
}
}
php_info_print_table_start();
php_info_print_table_row(2, "Session Support", "enabled" );
if (save_handlers.s) {
smart_str_0(&save_handlers);
php_info_print_table_row(2, "Registered save handlers", ZSTR_VAL(save_handlers.s));
smart_str_free(&save_handlers);
} else {
php_info_print_table_row(2, "Registered save handlers", "none");
}
if (ser_handlers.s) {
smart_str_0(&ser_handlers);
php_info_print_table_row(2, "Registered serializer handlers", ZSTR_VAL(ser_handlers.s));
smart_str_free(&ser_handlers);
} else {
php_info_print_table_row(2, "Registered serializer handlers", "none");
}
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
static const zend_module_dep session_deps[] = { /* {{{ */
ZEND_MOD_OPTIONAL("hash")
ZEND_MOD_REQUIRED("spl")
ZEND_MOD_END
};
/* }}} */
/* ************************
* Upload hook handling *
************************ */
static zend_bool early_find_sid_in(zval *dest, int where, php_session_rfc1867_progress *progress) /* {{{ */
{
zval *ppid;
if (Z_ISUNDEF(PG(http_globals)[where])) {
return 0;
}
if ((ppid = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[where]), PS(session_name), progress->sname_len))
&& Z_TYPE_P(ppid) == IS_STRING) {
zval_dtor(dest);
ZVAL_DEREF(ppid);
ZVAL_COPY(dest, ppid);
return 1;
}
return 0;
} /* }}} */
static void php_session_rfc1867_early_find_sid(php_session_rfc1867_progress *progress) /* {{{ */
{
if (PS(use_cookies)) {
sapi_module.treat_data(PARSE_COOKIE, NULL, NULL);
if (early_find_sid_in(&progress->sid, TRACK_VARS_COOKIE, progress)) {
progress->apply_trans_sid = 0;
return;
}
}
if (PS(use_only_cookies)) {
return;
}
sapi_module.treat_data(PARSE_GET, NULL, NULL);
early_find_sid_in(&progress->sid, TRACK_VARS_GET, progress);
} /* }}} */
static zend_bool php_check_cancel_upload(php_session_rfc1867_progress *progress) /* {{{ */
{
zval *progress_ary, *cancel_upload;
if ((progress_ary = zend_symtable_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), progress->key.s)) == NULL) {
return 0;
}
if (Z_TYPE_P(progress_ary) != IS_ARRAY) {
return 0;
}
if ((cancel_upload = zend_hash_str_find(Z_ARRVAL_P(progress_ary), "cancel_upload", sizeof("cancel_upload") - 1)) == NULL) {
return 0;
}
return Z_TYPE_P(cancel_upload) == IS_TRUE;
} /* }}} */
static void php_session_rfc1867_update(php_session_rfc1867_progress *progress, int force_update) /* {{{ */
{
if (!force_update) {
if (Z_LVAL_P(progress->post_bytes_processed) < progress->next_update) {
return;
}
#ifdef HAVE_GETTIMEOFDAY
if (PS(rfc1867_min_freq) > 0.0) {
struct timeval tv = {0};
double dtv;
gettimeofday(&tv, NULL);
dtv = (double) tv.tv_sec + tv.tv_usec / 1000000.0;
if (dtv < progress->next_update_time) {
return;
}
progress->next_update_time = dtv + PS(rfc1867_min_freq);
}
#endif
progress->next_update = Z_LVAL_P(progress->post_bytes_processed) + progress->update_step;
}
php_session_initialize();
PS(session_status) = php_session_active;
IF_SESSION_VARS() {
zval *sess_var = Z_REFVAL(PS(http_session_vars));
SEPARATE_ARRAY(sess_var);
progress->cancel_upload |= php_check_cancel_upload(progress);
Z_TRY_ADDREF(progress->data);
zend_hash_update(Z_ARRVAL_P(sess_var), progress->key.s, &progress->data);
}
php_session_flush(1);
} /* }}} */
static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress) /* {{{ */
{
php_session_initialize();
PS(session_status) = php_session_active;
IF_SESSION_VARS() {
zval *sess_var = Z_REFVAL(PS(http_session_vars));
SEPARATE_ARRAY(sess_var);
zend_hash_del(Z_ARRVAL_P(sess_var), progress->key.s);
}
php_session_flush(1);
} /* }}} */
static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra) /* {{{ */
{
php_session_rfc1867_progress *progress;
int retval = SUCCESS;
if (php_session_rfc1867_orig_callback) {
retval = php_session_rfc1867_orig_callback(event, event_data, extra);
}
if (!PS(rfc1867_enabled)) {
return retval;
}
progress = PS(rfc1867_progress);
switch(event) {
case MULTIPART_EVENT_START: {
multipart_event_start *data = (multipart_event_start *) event_data;
progress = ecalloc(1, sizeof(php_session_rfc1867_progress));
progress->content_length = data->content_length;
progress->sname_len = strlen(PS(session_name));
PS(rfc1867_progress) = progress;
}
break;
case MULTIPART_EVENT_FORMDATA: {
multipart_event_formdata *data = (multipart_event_formdata *) event_data;
size_t value_len;
if (Z_TYPE(progress->sid) && progress->key.s) {
break;
}
/* orig callback may have modified *data->newlength */
if (data->newlength) {
value_len = *data->newlength;
} else {
value_len = data->length;
}
if (data->name && data->value && value_len) {
size_t name_len = strlen(data->name);
if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) {
zval_dtor(&progress->sid);
ZVAL_STRINGL(&progress->sid, (*data->value), value_len);
} else if (name_len == strlen(PS(rfc1867_name)) && memcmp(data->name, PS(rfc1867_name), name_len + 1) == 0) {
smart_str_free(&progress->key);
smart_str_appends(&progress->key, PS(rfc1867_prefix));
smart_str_appendl(&progress->key, *data->value, value_len);
smart_str_0(&progress->key);
progress->apply_trans_sid = APPLY_TRANS_SID;
php_session_rfc1867_early_find_sid(progress);
}
}
}
break;
case MULTIPART_EVENT_FILE_START: {
multipart_event_file_start *data = (multipart_event_file_start *) event_data;
/* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set
* or when we have no session id */
if (!Z_TYPE(progress->sid) || !progress->key.s) {
break;
}
/* First FILE_START event, initializing data */
if (Z_ISUNDEF(progress->data)) {
if (PS(rfc1867_freq) >= 0) {
progress->update_step = PS(rfc1867_freq);
} else if (PS(rfc1867_freq) < 0) { /* % of total size */
progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100;
}
progress->next_update = 0;
progress->next_update_time = 0.0;
array_init(&progress->data);
array_init(&progress->files);
add_assoc_long_ex(&progress->data, "start_time", sizeof("start_time") - 1, (zend_long)sapi_get_request_time());
add_assoc_long_ex(&progress->data, "content_length", sizeof("content_length") - 1, progress->content_length);
add_assoc_long_ex(&progress->data, "bytes_processed", sizeof("bytes_processed") - 1, data->post_bytes_processed);
add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 0);
add_assoc_zval_ex(&progress->data, "files", sizeof("files") - 1, &progress->files);
progress->post_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->data), "bytes_processed", sizeof("bytes_processed") - 1);
php_rinit_session(0);
PS(id) = zend_string_init(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid), 0);
if (progress->apply_trans_sid) {
/* Enable trans sid by modifying flags */
PS(use_trans_sid) = 1;
PS(use_only_cookies) = 0;
}
PS(send_cookie) = 0;
}
array_init(&progress->current_file);
/* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */
add_assoc_string_ex(&progress->current_file, "field_name", sizeof("field_name") - 1, data->name);
add_assoc_string_ex(&progress->current_file, "name", sizeof("name") - 1, *data->filename);
add_assoc_null_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1);
add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, 0);
add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 0);
add_assoc_long_ex(&progress->current_file, "start_time", sizeof("start_time") - 1, (zend_long)time(NULL));
add_assoc_long_ex(&progress->current_file, "bytes_processed", sizeof("bytes_processed") - 1, 0);
add_next_index_zval(&progress->files, &progress->current_file);
progress->current_file_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->current_file), "bytes_processed", sizeof("bytes_processed") - 1);
Z_LVAL_P(progress->current_file_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0);
}
break;
case MULTIPART_EVENT_FILE_DATA: {
multipart_event_file_data *data = (multipart_event_file_data *) event_data;
if (!Z_TYPE(progress->sid) || !progress->key.s) {
break;
}
Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length;
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0);
}
break;
case MULTIPART_EVENT_FILE_END: {
multipart_event_file_end *data = (multipart_event_file_end *) event_data;
if (!Z_TYPE(progress->sid) || !progress->key.s) {
break;
}
if (data->temp_filename) {
add_assoc_string_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1, data->temp_filename);
}
add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, data->cancel_upload);
add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 1);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 0);
}
break;
case MULTIPART_EVENT_END: {
multipart_event_end *data = (multipart_event_end *) event_data;
if (Z_TYPE(progress->sid) && progress->key.s) {
if (PS(rfc1867_cleanup)) {
php_session_rfc1867_cleanup(progress);
} else {
SEPARATE_ARRAY(&progress->data);
add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 1);
Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
php_session_rfc1867_update(progress, 1);
}
php_rshutdown_session_globals();
}
if (!Z_ISUNDEF(progress->data)) {
zval_ptr_dtor(&progress->data);
}
zval_ptr_dtor(&progress->sid);
smart_str_free(&progress->key);
efree(progress);
progress = NULL;
PS(rfc1867_progress) = NULL;
}
break;
}
if (progress && progress->cancel_upload) {
return FAILURE;
}
return retval;
} /* }}} */
zend_module_entry session_module_entry = {
STANDARD_MODULE_HEADER_EX,
NULL,
session_deps,
"session",
session_functions,
PHP_MINIT(session), PHP_MSHUTDOWN(session),
PHP_RINIT(session), PHP_RSHUTDOWN(session),
PHP_MINFO(session),
PHP_SESSION_VERSION,
PHP_MODULE_GLOBALS(ps),
PHP_GINIT(ps),
NULL,
NULL,
STANDARD_MODULE_PROPERTIES_EX
};
#ifdef COMPILE_DL_SESSION
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(session)
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
|
/**
* Constructs a ULID generator closure that emits universally unique,
* monotonic values.
*
* let generator = ULID();
* let ulid0 = generator();
* let ulid1 = generator();
* assert(ulid0 < ulid1);
*/
function ULID() {
const BASE32 = [
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q',
'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z'
];
let last = -1;
/* Pre-allocate work buffers / views */
let ulid = new Uint8Array(16);
let time = new DataView(ulid.buffer, 0, 6);
let rand = new Uint8Array(ulid.buffer, 6, 10);
let dest = new Array(26);
function encode(ulid) {
dest[0] = BASE32[ ulid[0] >> 5];
dest[1] = BASE32[(ulid[0] >> 0) & 0x1f];
for (let i = 0; i < 3; i++) {
dest[i*8+2] = BASE32[ ulid[i*5+1] >> 3];
dest[i*8+3] = BASE32[(ulid[i*5+1] << 2 | ulid[i*5+2] >> 6) & 0x1f];
dest[i*8+4] = BASE32[(ulid[i*5+2] >> 1) & 0x1f];
dest[i*8+5] = BASE32[(ulid[i*5+2] << 4 | ulid[i*5+3] >> 4) & 0x1f];
dest[i*8+6] = BASE32[(ulid[i*5+3] << 1 | ulid[i*5+4] >> 7) & 0x1f];
dest[i*8+7] = BASE32[(ulid[i*5+4] >> 2) & 0x1f];
dest[i*8+8] = BASE32[(ulid[i*5+4] << 3 | ulid[i*5+5] >> 5) & 0x1f];
dest[i*8+9] = BASE32[(ulid[i*5+5] >> 0) & 0x1f];
}
return dest.join('');
}
return function() {
let now = Date.now();
if (now === last) {
/* 80-bit overflow is so incredibly unlikely that it's not
* considered as a possiblity here.
*/
for (let i = 9; i >= 0; i--)
if (rand[i]++ < 255)
break;
} else {
last = now;
time.setUint16(0, (now / 4294967296.0) | 0);
time.setUint32(2, now | 0);
window.crypto.getRandomValues(rand);
}
return encode(ulid);
};
}
|
"""
WSGI config for qts_app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qts_app.settings')
application = get_wsgi_application()
|
mycallback( {"CONTRIBUTOR OCCUPATION": "Administrative Staff Secretary", "CONTRIBUTION AMOUNT (F3L Bundled)": "5.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "INT'L ASSOCIATION OF MACHINISTS", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "38140 PLEASANT VIEW DRIVE", "CONTRIBUTOR MIDDLE NAME": "J", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "MD", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "LISA", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20110415", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00002469", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "HYDE", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "20622", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "CHARLOTTE HAL", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "19079983", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727386.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "245.00", "FORM TYPE": "SA11ai"});
|
module.exports = {
mode: 'jit',
/*purge: [],*/
purge: ['./src/pages/**/*.{js,ts,jsx,tsx}', './src/components/!**/!*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
|
(function(window) { // 防止污染全局变量
var zepto = {};
function Z (dom, selector) { // 构造函数
var i, len = dom? dom.length : 0;
for (i = 0; i < len; i++) { // 初始化时候挂载到每个实例上
this[i] = dom[i];
}
this.length = len;
this.selector = selector || '';
}
zepto.Z = function(dom, selector) { // 返回Z构造函数的实例
return new Z(dom, selector);
}
zepto.init = function(selector) {
var slice = Array.prototype.slice;
var dom = slice.call(document.querySelectorAll(selector)); // dom数组
return zepto.Z(dom, selector); // 返回zepto.Z方法
}
var $ = function(selector) { // 方法返回zepto.init(选择器)
return zepto.init(selector);
}
$.fn = { // 原型上的方法css, html等
constructor: Z,
css: function() {
alert('css')
},
html: function() {
alert('html')
}
}
window.$ = $; // 把$暴露到全局
Z.prototype = $.fn;
})(window)
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _package = { version: '3.23.3' };
var _default = _package.version;
exports["default"] = _default;
//# sourceMappingURL=index.js.map
|
var Discord = require('discord.js');
var auth = require('../.secure/auth.json');
const prefix = '.';
const calcDust = (level, special, isNew) => {
var baseOwned = 100;
var baseUnowned = 20000;
var baseOwnedSpecial = 20000;
var baseUnownedSpecial = 1000000;
var modifiers = {
good : 1,
great: 0.8,
ultra: 0.08,
best: 0.04
}
var dustBase = 0;
if(!special && !isNew){
return baseOwned; // special case
}
if(!special && isNew){
dustBase = baseUnowned
}
if(special && !isNew){
dustBase = baseOwnedSpecial
}
if(special && isNew){
dustBase = baseUnownedSpecial
}
return modifiers[level] * dustBase;
}
// Initialize Discord Bot
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === "ping"){
message.channel.send("pong!");
}
if(command === "dust"){
// get the args
let friend = args[0];
let special = args[1] == "yes";
let isNew = args[2] == "yes";
var dust = calcDust(friend, special, isNew)
message.channel.send("Dust calc... " + dust);
}
}
});
client.login(auth.token);
|
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from moto.ec2.models import ec2_backends
from .models import rds2_backends
import json
import re
class RDS2Response(BaseResponse):
@property
def backend(self):
return rds2_backends[self.region]
def _get_db_kwargs(self):
args = {
"auto_minor_version_upgrade": self._get_param('AutoMinorVersionUpgrade'),
"allocated_storage": self._get_int_param('AllocatedStorage'),
"availability_zone": self._get_param("AvailabilityZone"),
"backup_retention_period": self._get_param("BackupRetentionPeriod"),
"db_instance_class": self._get_param('DBInstanceClass'),
"db_instance_identifier": self._get_param('DBInstanceIdentifier'),
"db_name": self._get_param("DBName"),
# DBParameterGroupName
"db_subnet_group_name": self._get_param("DBSubnetGroupName"),
"engine": self._get_param("Engine"),
"engine_version": self._get_param("EngineVersion"),
"iops": self._get_int_param("Iops"),
"master_user_password": self._get_param('MasterUserPassword'),
"master_username": self._get_param('MasterUsername'),
"multi_az": self._get_bool_param("MultiAZ"),
# OptionGroupName
"port": self._get_param('Port'),
# PreferredBackupWindow
# PreferredMaintenanceWindow
"publicly_accessible": self._get_param("PubliclyAccessible"),
"region": self.region,
"security_groups": self._get_multi_param('DBSecurityGroups.member'),
"storage_type": self._get_param("StorageType"),
# VpcSecurityGroupIds.member.N
"tags": list()
}
args['tags'] = self.unpack_complex_list_params('Tags.member', ('Key', 'Value'))
return args
def _get_db_replica_kwargs(self):
return {
"auto_minor_version_upgrade": self._get_param('AutoMinorVersionUpgrade'),
"availability_zone": self._get_param("AvailabilityZone"),
"db_instance_class": self._get_param('DBInstanceClass'),
"db_instance_identifier": self._get_param('DBInstanceIdentifier'),
"db_subnet_group_name": self._get_param("DBSubnetGroupName"),
"iops": self._get_int_param("Iops"),
# OptionGroupName
"port": self._get_param('Port'),
"publicly_accessible": self._get_param("PubliclyAccessible"),
"source_db_identifier": self._get_param('SourceDBInstanceIdentifier'),
"storage_type": self._get_param("StorageType"),
}
def _get_option_group_kwargs(self):
return {
'major_engine_version': self._get_param('MajorEngineVersion'),
'description': self._get_param('OptionGroupDescription'),
'engine_name': self._get_param('EngineName'),
'name': self._get_param('OptionGroupName')
}
def unpack_complex_list_params(self, label, names):
unpacked_list = list()
count = 1
while self._get_param('{0}.{1}.{2}'.format(label, count, names[0])):
param = dict()
for i in range(len(names)):
param[names[i]] = self._get_param('{0}.{1}.{2}'.format(label, count, names[i]))
unpacked_list.append(param)
count += 1
return unpacked_list
def unpack_list_params(self, label):
unpacked_list = list()
count = 1
while self._get_param('{0}.{1}'.format(label, count)):
unpacked_list.append(self._get_param('{0}.{1}'.format(label, count)))
count += 1
return unpacked_list
def create_dbinstance(self):
return self.create_db_instance()
def create_db_instance(self):
db_kwargs = self._get_db_kwargs()
database = self.backend.create_database(db_kwargs)
template = self.response_template(CREATE_DATABASE_TEMPLATE)
return template.render(database=database)
def create_dbinstance_read_replica(self):
return self.create_db_instance_read_replica()
def create_db_instance_read_replica(self):
db_kwargs = self._get_db_replica_kwargs()
database = self.backend.create_database_replica(db_kwargs)
template = self.response_template(CREATE_DATABASE_REPLICA_TEMPLATE)
return template.render(database=database)
def describe_dbinstances(self):
return self.describe_db_instances()
def describe_db_instances(self):
db_instance_identifier = self._get_param('DBInstanceIdentifier')
databases = self.backend.describe_databases(db_instance_identifier)
template = self.response_template(DESCRIBE_DATABASES_TEMPLATE)
return template.render(databases=databases)
def modify_dbinstance(self):
return self.modify_db_instance()
def modify_db_instance(self):
db_instance_identifier = self._get_param('DBInstanceIdentifier')
db_kwargs = self._get_db_kwargs()
database = self.backend.modify_database(db_instance_identifier, db_kwargs)
template = self.response_template(MODIFY_DATABASE_TEMPLATE)
return template.render(database=database)
def delete_dbinstance(self):
return self.delete_db_instance()
def delete_db_instance(self):
db_instance_identifier = self._get_param('DBInstanceIdentifier')
database = self.backend.delete_database(db_instance_identifier)
template = self.response_template(DELETE_DATABASE_TEMPLATE)
return template.render(database=database)
def reboot_dbinstance(self):
return self.reboot_db_instance()
def reboot_db_instance(self):
db_instance_identifier = self._get_param('DBInstanceIdentifier')
database = self.backend.reboot_db_instance(db_instance_identifier)
template = self.response_template(REBOOT_DATABASE_TEMPLATE)
return template.render(database=database)
def list_tags_for_resource(self):
arn = self._get_param('ResourceName')
template = self.response_template(LIST_TAGS_FOR_RESOURCE_TEMPLATE)
tags = self.backend.list_tags_for_resource(arn)
return template.render(tags=tags)
def add_tags_to_resource(self):
arn = self._get_param('ResourceName')
tags = self.unpack_complex_list_params('Tags.member', ('Key', 'Value'))
tags = self.backend.add_tags_to_resource(arn, tags)
template = self.response_template(ADD_TAGS_TO_RESOURCE_TEMPLATE)
return template.render(tags=tags)
def remove_tags_from_resource(self):
arn = self._get_param('ResourceName')
tag_keys = self.unpack_list_params('TagKeys.member')
self.backend.remove_tags_from_resource(arn, tag_keys)
template = self.response_template(REMOVE_TAGS_FROM_RESOURCE_TEMPLATE)
return template.render()
def create_dbsecurity_group(self):
return self.create_db_security_group()
def create_db_security_group(self):
group_name = self._get_param('DBSecurityGroupName')
description = self._get_param('DBSecurityGroupDescription')
security_group = self.backend.create_security_group(group_name, description)
template = self.response_template(CREATE_SECURITY_GROUP_TEMPLATE)
return template.render(security_group=security_group)
def describe_dbsecurity_groups(self):
return self.describe_db_security_groups()
def describe_db_security_groups(self):
security_group_name = self._get_param('DBSecurityGroupName')
security_groups = self.backend.describe_security_groups(security_group_name)
template = self.response_template(DESCRIBE_SECURITY_GROUPS_TEMPLATE)
return template.render(security_groups=security_groups)
def delete_dbsecurity_group(self):
return self.delete_db_security_group()
def delete_db_security_group(self):
security_group_name = self._get_param('DBSecurityGroupName')
security_group = self.backend.delete_security_group(security_group_name)
template = self.response_template(DELETE_SECURITY_GROUP_TEMPLATE)
return template.render(security_group=security_group)
def authorize_dbsecurity_group_ingress(self):
return self.authorize_db_security_group_ingress()
def authorize_db_security_group_ingress(self):
security_group_name = self._get_param('DBSecurityGroupName')
cidr_ip = self._get_param('CIDRIP')
security_group = self.backend.authorize_security_group(security_group_name, cidr_ip)
template = self.response_template(AUTHORIZE_SECURITY_GROUP_TEMPLATE)
return template.render(security_group=security_group)
def create_dbsubnet_group(self):
return self.create_db_subnet_group()
def create_db_subnet_group(self):
subnet_name = self._get_param('DBSubnetGroupName')
description = self._get_param('DBSubnetGroupDescription')
subnet_ids = self._get_multi_param('SubnetIds.member')
subnets = [ec2_backends[self.region].get_subnet(subnet_id) for subnet_id in subnet_ids]
subnet_group = self.backend.create_subnet_group(subnet_name, description, subnets)
template = self.response_template(CREATE_SUBNET_GROUP_TEMPLATE)
return template.render(subnet_group=subnet_group)
def describe_dbsubnet_groups(self):
return self.describe_db_subnet_groups()
def describe_db_subnet_groups(self):
subnet_name = self._get_param('DBSubnetGroupName')
subnet_groups = self.backend.describe_subnet_groups(subnet_name)
template = self.response_template(DESCRIBE_SUBNET_GROUPS_TEMPLATE)
return template.render(subnet_groups=subnet_groups)
def delete_dbsubnet_group(self):
return self.delete_db_subnet_group()
def delete_db_subnet_group(self):
subnet_name = self._get_param('DBSubnetGroupName')
subnet_group = self.backend.delete_subnet_group(subnet_name)
template = self.response_template(DELETE_SUBNET_GROUP_TEMPLATE)
return template.render(subnet_group=subnet_group)
def create_option_group(self):
kwargs = self._get_option_group_kwargs()
option_group = self.backend.create_option_group(kwargs)
template = self.response_template(CREATE_OPTION_GROUP_TEMPLATE)
return template.render(option_group=option_group)
def delete_option_group(self):
kwargs = self._get_option_group_kwargs()
option_group = self.backend.delete_option_group(kwargs['name'])
template = self.response_template(DELETE_OPTION_GROUP_TEMPLATE)
return template.render(option_group=option_group)
def describe_option_groups(self):
kwargs = self._get_option_group_kwargs()
kwargs['max_records'] = self._get_param('MaxRecords')
kwargs['marker'] = self._get_param('Marker')
option_groups = self.backend.describe_option_groups(kwargs)
template = self.response_template(DESCRIBE_OPTION_GROUP_TEMPLATE)
return template.render(option_groups=option_groups)
def describe_option_group_options(self):
engine_name = self._get_param('EngineName')
major_engine_version = self._get_param('MajorEngineVersion')
option_group_options = self.backend.describe_option_group_options(engine_name, major_engine_version)
return option_group_options
def modify_option_group(self):
option_group_name = self._get_param('OptionGroupName')
count = 1
options_to_include = []
while self._get_param('OptionsToInclude.member.{0}.OptionName'.format(count)):
options_to_include.append({
'Port': self._get_param('OptionsToInclude.member.{0}.Port'.format(count)),
'OptionName': self._get_param('OptionsToInclude.member.{0}.OptionName'.format(count)),
'DBSecurityGroupMemberships': self._get_param('OptionsToInclude.member.{0}.DBSecurityGroupMemberships'.format(count)),
'OptionSettings': self._get_param('OptionsToInclude.member.{0}.OptionSettings'.format(count)),
'VpcSecurityGroupMemberships': self._get_param('OptionsToInclude.member.{0}.VpcSecurityGroupMemberships'.format(count))
})
count += 1
count = 1
options_to_remove = []
while self._get_param('OptionsToRemove.member.{0}'.format(count)):
options_to_remove.append(self._get_param('OptionsToRemove.member.{0}'.format(count)))
count += 1
apply_immediately = self._get_param('ApplyImmediately')
option_group = self.backend.modify_option_group(option_group_name,
options_to_include,
options_to_remove,
apply_immediately)
template = self.response_template(MODIFY_OPTION_GROUP_TEMPLATE)
return template.render(option_group=option_group)
CREATE_DATABASE_TEMPLATE = """{
"CreateDBInstanceResponse": {
"CreateDBInstanceResult": {
"DBInstance": {{ database.to_json() }}
},
"ResponseMetadata": { "RequestId": "523e3218-afc7-11c3-90f5-f90431260ab4" }
}
}"""
CREATE_DATABASE_REPLICA_TEMPLATE = """{"CreateDBInstanceReadReplicaResponse": {
"ResponseMetadata": {
"RequestId": "5e60c46d-a844-11e4-bb68-17f36418e58f"
},
"CreateDBInstanceReadReplicaResult": {
"DBInstance": {{ database.to_json() }}
}
}}"""
DESCRIBE_DATABASES_TEMPLATE = """{
"DescribeDBInstancesResponse": {
"DescribeDBInstancesResult": {
"DBInstances": [
{%- for database in databases -%}
{%- if loop.index != 1 -%},{%- endif -%}
{{ database.to_json() }}
{%- endfor -%}
]
},
"ResponseMetadata": { "RequestId": "523e3218-afc7-11c3-90f5-f90431260ab4" }
}
}"""
MODIFY_DATABASE_TEMPLATE = """{"ModifyDBInstanceResponse": {
"ModifyDBInstanceResult": {
"DBInstance": {{ database.to_json() }},
"ResponseMetadata": {
"RequestId": "bb58476c-a1a8-11e4-99cf-55e92d4bbada"
}
}
}
}"""
REBOOT_DATABASE_TEMPLATE = """{"RebootDBInstanceResponse": {
"RebootDBInstanceResult": {
"DBInstance": {{ database.to_json() }},
"ResponseMetadata": {
"RequestId": "d55711cb-a1ab-11e4-99cf-55e92d4bbada"
}
}
}
}"""
DELETE_DATABASE_TEMPLATE = """{ "DeleteDBInstanceResponse": {
"DeleteDBInstanceResult": {
"DBInstance": {{ database.to_json() }}
},
"ResponseMetadata": {
"RequestId": "523e3218-afc7-11c3-90f5-f90431260ab4"
}
}
}"""
CREATE_SECURITY_GROUP_TEMPLATE = """{"CreateDBSecurityGroupResponse": {
"CreateDBSecurityGroupResult": {
"DBSecurityGroup":
{{ security_group.to_json() }},
"ResponseMetadata": {
"RequestId": "462165d0-a77a-11e4-a5fa-75b30c556f97"
}}
}
}"""
DESCRIBE_SECURITY_GROUPS_TEMPLATE = """{
"DescribeDBSecurityGroupsResponse": {
"ResponseMetadata": {
"RequestId": "5df2014e-a779-11e4-bdb0-594def064d0c"
},
"DescribeDBSecurityGroupsResult": {
"Marker": "null",
"DBSecurityGroups": [
{% for security_group in security_groups %}
{%- if loop.index != 1 -%},{%- endif -%}
{{ security_group.to_json() }}
{% endfor %}
]
}
}
}"""
DELETE_SECURITY_GROUP_TEMPLATE = """{"DeleteDBSecurityGroupResponse": {
"ResponseMetadata": {
"RequestId": "97e846bd-a77d-11e4-ac58-91351c0f3426"
}
}}"""
AUTHORIZE_SECURITY_GROUP_TEMPLATE = """{
"AuthorizeDBSecurityGroupIngressResponse": {
"AuthorizeDBSecurityGroupIngressResult": {
"DBSecurityGroup": {{ security_group.to_json() }}
},
"ResponseMetadata": {
"RequestId": "75d32fd5-a77e-11e4-8892-b10432f7a87d"
}
}
}"""
CREATE_SUBNET_GROUP_TEMPLATE = """{
"CreateDBSubnetGroupResponse": {
"CreateDBSubnetGroupResult":
{ {{ subnet_group.to_json() }} },
"ResponseMetadata": { "RequestId": "3a401b3f-bb9e-11d3-f4c6-37db295f7674" }
}
}"""
DESCRIBE_SUBNET_GROUPS_TEMPLATE = """{
"DescribeDBSubnetGroupsResponse": {
"DescribeDBSubnetGroupsResult": {
"DBSubnetGroups": [
{% for subnet_group in subnet_groups %}
{ {{ subnet_group.to_json() }} }{%- if not loop.last -%},{%- endif -%}
{% endfor %}
],
"Marker": null
},
"ResponseMetadata": { "RequestId": "b783db3b-b98c-11d3-fbc7-5c0aad74da7c" }
}
}"""
DELETE_SUBNET_GROUP_TEMPLATE = """{"DeleteDBSubnetGroupResponse": {"ResponseMetadata": {"RequestId": "13785dd5-a7fc-11e4-bb9c-7f371d0859b0"}}}"""
CREATE_OPTION_GROUP_TEMPLATE = """{
"CreateOptionGroupResponse": {
"CreateOptionGroupResult": {
"OptionGroup": {{ option_group.to_json() }}
},
"ResponseMetadata": {
"RequestId": "1e38dad4-9f50-11e4-87ea-a31c60ed2e36"
}
}
}"""
DELETE_OPTION_GROUP_TEMPLATE = \
"""{"DeleteOptionGroupResponse": {"ResponseMetadata": {"RequestId": "e2590367-9fa2-11e4-99cf-55e92d41c60e"}}}"""
DESCRIBE_OPTION_GROUP_TEMPLATE = \
"""{"DescribeOptionGroupsResponse": {
"DescribeOptionGroupsResult": {
"Marker": null,
"OptionGroupsList": [
{%- for option_group in option_groups -%}
{%- if loop.index != 1 -%},{%- endif -%}
{{ option_group.to_json() }}
{%- endfor -%}
]},
"ResponseMetadata": {"RequestId": "4caf445d-9fbc-11e4-87ea-a31c60ed2e36"}
}}"""
DESCRIBE_OPTION_GROUP_OPTIONS_TEMPLATE = \
"""{"DescribeOptionGroupOptionsResponse": {
"DescribeOptionGroupOptionsResult": {
"Marker": null,
"OptionGroupOptions": [
{%- for option_group_option in option_group_options -%}
{%- if loop.index != 1 -%},{%- endif -%}
{{ option_group_option.to_json() }}
{%- endfor -%}
]},
"ResponseMetadata": {"RequestId": "457f7bb8-9fbf-11e4-9084-5754f80d5144"}
}}"""
MODIFY_OPTION_GROUP_TEMPLATE = \
"""{"ModifyOptionGroupResponse": {
"ResponseMetadata": {
"RequestId": "ce9284a5-a0de-11e4-b984-a11a53e1f328"
},
"ModifyOptionGroupResult":
{{ option_group.to_json() }}
}
}"""
LIST_TAGS_FOR_RESOURCE_TEMPLATE = \
"""{"ListTagsForResourceResponse":
{"ListTagsForResourceResult":
{"TagList": [
{%- for tag in tags -%}
{%- if loop.index != 1 -%},{%- endif -%}
{
"Key": "{{ tag['Key'] }}",
"Value": "{{ tag['Value'] }}"
}
{%- endfor -%}
]},
"ResponseMetadata": {
"RequestId": "8c21ba39-a598-11e4-b688-194eaf8658fa"
}
}
}"""
ADD_TAGS_TO_RESOURCE_TEMPLATE = \
"""{"ListTagsForResourceResponse": {
"ListTagsForResourceResult": {
"TagList": [
{%- for tag in tags -%}
{%- if loop.index != 1 -%},{%- endif -%}
{
"Key": "{{ tag['Key'] }}",
"Value": "{{ tag['Value'] }}"
}
{%- endfor -%}
]},
"ResponseMetadata": {
"RequestId": "b194d9ca-a664-11e4-b688-194eaf8658fa"
}
}
}"""
REMOVE_TAGS_FROM_RESOURCE_TEMPLATE = \
"""{"RemoveTagsFromResourceResponse": {"ResponseMetadata": {"RequestId": "c6499a01-a664-11e4-8069-fb454b71a80e"}}}
"""
|
module.exports = {
entry: "./src/js/index.js",
node: {
fs: "empty",
net: "empty"
},
output: {
path: __dirname,
filename: "bundle.js"
}
}
|
/**
* @license
* Copyright 2019 Google LLC.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import {MessagePort} from '../../../build/runtime/message-channel.js';
class PecPort extends MessagePort {
constructor(pecId, idGenerator, bus) {
super();
this.pecId = pecId;
this.sessionId = idGenerator.currentSessionIdForTesting;
this.bus = bus;
}
close() {}
postMessage(msg) {
msg['id'] = this.pecId.toString();
if (this.sessionId) {
// Only send the sessionId in the very first pec call to initialize the ID generator.
msg['sessionId'] = this.sessionId;
this.sessionId = null;
}
this.bus.send({message: 'pec', data: msg});
}
set onmessage(callback) {
this.callback = callback;
}
}
const pecPorts = {};
export const portIndustry = (bus) => {
return (pecId, idGenerator) => {
const port = new PecPort(pecId, idGenerator, bus);
pecPorts[pecId] = port;
return port;
};
};
export const handlePecMessage = (msg) => {
if (!pecPorts[msg.id]) {
console.error(`Cannot find port for ${msg.id}`);
}
pecPorts[msg.id].callback({data: msg.entity});
};
|
//
// PhoneFactory.h
// FactoryMethodPattern
//
// Created by chenqg on 2019/10/30.
// Copyright © 2019 chenqg. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Phone.h"
NS_ASSUME_NONNULL_BEGIN
@interface PhoneFactory : NSObject
+ (Phone *)createPhone;
@end
NS_ASSUME_NONNULL_END
|
import asyncio
async def app(scope, receive, send):
assert scope['type'] == 'http'
data = [b'Welcome to Django',b'3.0']
await send({
'type':'http.response.start',
'status':200,
'headers':[ [b'content-type',b'text/html'] ],
})
for chunk in data:
await send({
'type':'http.response.body',
'body':chunk,
'more_body': True
})
await asyncio.sleep(1)
await send({
'type':'http.response.body',
'body':b'<h1>Django ASGI APp is finally here!!</h1>',
'more_body':True
})
await asyncio.sleep(1)
await send({
'type':'http.response.body',
'body':b"Let's get busy!!",
'more_body':False
})
|
#!/usr/bin/env node
var fis = module.exports = require('fis3');
//先把rake加到插件查找中
fis.require.prefixes.unshift('rake');
fis.require.prefixes.unshift('kys');
fis.cli.name = 'kys';
fis.cli.info = require('./package.json');
//文件过滤设置
fis.set('project.ignore', ['node_modules/!**', 'output/!**', 'fis-conf.js']);
//默认设置
fis.set('statics', '../node_modules/.ky-release-webroot');
fis.set('namespace', '');
fis.set('domain', '');
fis.hook('relative');
fis.hook('cmd');
fis.match('**', {
useMap: true,
useHash: true,
relative: true,
release: false,
preprocessor: fis.plugin('replacer', {
ext: '.js',
from: /(['"])common:(components|widget|static)/g,
to: '$1as-common:$2'
})
})
// 重要,去掉 seajs-config.js 无法加载
.match('/static/(**)', {
isMod: true,
release: '${statics}/${namespace}/$1'
})
//assets处理
.match('/(assets/**)', {
url: '${namespace}/$1',
release: '${statics}/${namespace}/$1',
isMod: true,
})
//views处理
.match('/(views/**.html)', {
url: '${namespace}/$1',
release: '${statics}/${namespace}/$1',
isMod: true
})
//widget处理
.match('/(widget/**)', {
url: '${namespace}/$1',
release: '${statics}/${namespace}/$1',
isMod: true
})
.match('(**).tmpl', {
url: '${namespace}/$1',
release: '${statics}/${namespace}/$1',
rExt: '.js',
isMod: true,
parser: [fis.plugin('bdtmpl', {
LEFT_DELIMITER: '<%',
RIGHT_DELIMITER: '%>'
})]
})
.match('/**.js', {
isMod: true,
optimizer: fis.plugin('uglify-js'),
useHash: true,
postprocessor: fis.plugin('cmdwrap')
})
.match('/static/lib/(**)', {
useHash: false,
useCompile: false,
useParser: false,
usePreprocessor: false,
useStandard: false,
usePostprocessor: false,
isMod: false,
parser: false
})
//供模板使用
.match('/(manifest.json)', {
useHash: false,
release: '${statics}/${namespace}/$1'
})
.match('::image', {
useMap: true
})
.match('/**.less', {
parser: [fis.plugin('less-common'), fis.plugin('less')], //启用fis-parser-less插件
rExt: '.css'
})
.match('/**.{css,less}', {
optimizer: fis.plugin('clean-css'),
//autoprefixer 前缀处理
postprocessor: fis.plugin("autoprefixer", {
"browsers": ['last 2 versions', '> 5%', 'ie 8'],
"flexboxfixer": true,
"gradientfixer": true
})
})
;
fis.match('::packager', {
postpackager: fis.plugin('seajs')
});
// 注意: fis 中的 sea.js 方案,不支持部分打包。
// 所以不要去配置 packTo 了,运行时会报错的。
//本地测试环境
fis.media('debug').match('/**', {
useHash: false,
useSprite: false,
optimizer: null,
domain: '${domain}',
deploy: fis.plugin('local-deliver', {
to: '../'
})
});
//dev环境 不压缩
fis.media('dev')
.match('/**', {
optimizer: null,
domain: '${domain}',
deploy: fis.plugin('local-deliver', {
to: '../'
})
});
//prod环境 开启压缩
fis.media('prod')
.match('/**', {
domain: '${domain}',
deploy: fis.plugin('local-deliver', {
to: '../'
})
});
|
$(function () {
$('#container').highcharts('StockChart', {
rangeSelector: {
enabled: false
},
navigator: {
enabled: false
},
scrollbar: {
enabled: false
},
title: {
text: "Marker overflow"
},
subtitle: {
text: "Values below 100 should be clipped"
},
xAxis: {
labels: {
formatter: function () {
return this.value;
}
}
},
yAxis: [{
height: "40%",
min: 100,
max: 200,
tickInterval: 20,
startOnTick: false
}],
plotOptions: {
series: {
marker: {
enabled: true,
radius: 5
}
}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
});
|
"""
Ory APIs
Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501
The version of the OpenAPI document: v0.0.1-alpha.9
Contact: support@ory.sh
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from ory_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
class HealthStatus(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
'status': (str,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'status': 'status', # noqa: E501
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""HealthStatus - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
status (str): Status always contains \"ok\".. [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
|
#!/usr/bin/python
from flask import Flask, request, json, Response
app = Flask(__name__)
@app.route('/', methods=['POST'])
def handlePost():
if 'application/json' in request.headers.get('Content-Type'):
raw = json.dumps(request.json)
print(raw)
with open('./log.txt', 'a+') as log:
log.write(raw + '\n\n')
return Response('OK', 200)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
|
/*
* Copyright (c) 2008-2015 Travis Geiselbrecht
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __KERNEL_THREAD_H
#define __KERNEL_THREAD_H
#include <sys/types.h>
#include <list.h>
#include <compiler.h>
#include <arch/defines.h>
#include <arch/ops.h>
#include <arch/thread.h>
#include <kernel/wait.h>
#include <kernel/spinlock.h>
#include <debug.h>
#if WITH_KERNEL_VM
/* forward declaration */
typedef struct vmm_aspace vmm_aspace_t;
#endif
__BEGIN_CDECLS;
/* thread stats for all build */
#define THREAD_STATS 1
/* debug-enable runtime checks */
#if LK_DEBUGLEVEL > 1
#define THREAD_STACK_HIGHWATER 1
#define THREAD_STACK_BOUNDS_CHECK 1
#ifndef THREAD_STACK_PADDING_SIZE
#define THREAD_STACK_PADDING_SIZE 256
#endif
#endif
enum thread_state {
THREAD_SUSPENDED = 0,
THREAD_READY,
THREAD_RUNNING,
THREAD_BLOCKED,
THREAD_SLEEPING,
THREAD_DEATH,
};
typedef int (*thread_start_routine)(void *arg);
/* thread local storage */
enum thread_tls_list {
#ifdef WITH_LIB_UTHREAD
TLS_ENTRY_UTHREAD,
#endif
#ifdef WITH_LIB_LKUSER
TLS_ENTRY_LKUSER,
#endif
MAX_TLS_ENTRY
};
#define THREAD_FLAG_DETACHED (1<<0)
#define THREAD_FLAG_FREE_STACK (1<<1)
#define THREAD_FLAG_FREE_STRUCT (1<<2)
#define THREAD_FLAG_REAL_TIME (1<<3)
#define THREAD_FLAG_IDLE (1<<4)
#define THREAD_FLAG_DEBUG_STACK_BOUNDS_CHECK (1<<5)
#define THREAD_MAGIC (0x74687264) // 'thrd'
#define THREAD_LINEBUFFER_LENGTH 128
typedef struct thread {
int magic;
struct list_node thread_list_node;
/* active bits */
struct list_node queue_node;
int priority;
enum thread_state state;
int remaining_quantum;
unsigned int flags;
#if WITH_SMP
int curr_cpu;
int pinned_cpu; /* only run on pinned_cpu if >= 0 */
#endif
#if WITH_KERNEL_VM
vmm_aspace_t *aspace;
#endif
/* accounting information */
lk_bigtime_t last_started_running_us;
/* Total time in THREAD_RUNNING state. If the thread is currently in
* THREAD_RUNNING state, this excludes the time it has accrued since it
* left the scheduler. */
lk_bigtime_t runtime_us;
/* if blocked, a pointer to the wait queue */
struct wait_queue *blocking_wait_queue;
status_t wait_queue_block_ret;
/* architecture stuff */
struct arch_thread arch;
/* stack stuff */
void *stack;
size_t stack_size;
/* entry point */
thread_start_routine entry;
void *arg;
/* return code */
int retcode;
struct wait_queue retcode_wait_queue;
/* thread local storage */
uintptr_t tls[MAX_TLS_ENTRY];
char name[32];
#if WITH_DEBUG_LINEBUFFER
// buffering for debug/klog output
size_t linebuffer_pos;
char linebuffer[THREAD_LINEBUFFER_LENGTH];
#endif
} thread_t;
#if WITH_SMP
#define thread_curr_cpu(t) ((t)->curr_cpu)
#define thread_pinned_cpu(t) ((t)->pinned_cpu)
#define thread_set_curr_cpu(t,c) ((t)->curr_cpu = (c))
#define thread_set_pinned_cpu(t, c) ((t)->pinned_cpu = (c))
#else
#define thread_curr_cpu(t) (0)
#define thread_pinned_cpu(t) (-1)
#define thread_set_curr_cpu(t,c) do {} while(0)
#define thread_set_pinned_cpu(t, c) do {} while(0)
#endif
/* thread priority */
#define NUM_PRIORITIES 32
#define LOWEST_PRIORITY 0
#define HIGHEST_PRIORITY (NUM_PRIORITIES - 1)
#define DPC_PRIORITY (NUM_PRIORITIES - 2)
#define IDLE_PRIORITY LOWEST_PRIORITY
#define LOW_PRIORITY (NUM_PRIORITIES / 4)
#define DEFAULT_PRIORITY (NUM_PRIORITIES / 2)
#define HIGH_PRIORITY ((NUM_PRIORITIES / 4) * 3)
/* stack size */
#ifdef CUSTOM_DEFAULT_STACK_SIZE
#define DEFAULT_STACK_SIZE CUSTOM_DEFAULT_STACK_SIZE
#else
#define DEFAULT_STACK_SIZE ARCH_DEFAULT_STACK_SIZE
#endif
/* functions */
void thread_init_early(void);
void thread_init(void);
void thread_become_idle(void) __NO_RETURN;
void thread_secondary_cpu_init_early(void);
void thread_secondary_cpu_entry(void) __NO_RETURN;
void thread_set_name(const char *name);
void thread_set_priority(int priority);
thread_t *thread_create(const char *name, thread_start_routine entry, void *arg, int priority, size_t stack_size);
thread_t *thread_create_etc(thread_t *t, const char *name, thread_start_routine entry, void *arg, int priority, void *stack, size_t stack_size);
status_t thread_resume(thread_t *);
void thread_exit(int retcode) __NO_RETURN;
void thread_sleep(lk_time_t delay);
status_t thread_detach(thread_t *t);
status_t thread_join(thread_t *t, int *retcode, lk_time_t timeout);
status_t thread_detach_and_resume(thread_t *t);
status_t thread_set_real_time(thread_t *t);
void dump_thread(thread_t *t);
void arch_dump_thread(thread_t *t);
void dump_all_threads(void);
/* scheduler routines */
void thread_yield(void); /* give up the cpu voluntarily */
void thread_preempt(void); /* get preempted (inserted into head of run queue) */
void thread_block(void); /* block on something and reschedule */
void thread_unblock(thread_t *t, bool resched); /* go back in the run queue */
#ifdef WITH_LIB_UTHREAD
void uthread_context_switch(thread_t *oldthread, thread_t *newthread);
#endif
/* called on every timer tick for the scheduler to do quantum expiration */
enum handler_return thread_timer_tick(void);
/* the current thread */
thread_t *get_current_thread(void);
void set_current_thread(thread_t *);
/* scheduler lock */
extern spin_lock_t thread_lock;
#define THREAD_LOCK(state) spin_lock_saved_state_t state; spin_lock_irqsave(&thread_lock, state)
#define THREAD_UNLOCK(state) spin_unlock_irqrestore(&thread_lock, state)
static inline bool thread_lock_held(void)
{
return spin_lock_held(&thread_lock);
}
/* thread local storage */
static inline __ALWAYS_INLINE uintptr_t tls_get(uint entry)
{
return get_current_thread()->tls[entry];
}
static inline __ALWAYS_INLINE uintptr_t __tls_set(uint entry, uintptr_t val)
{
uintptr_t oldval = get_current_thread()->tls[entry];
get_current_thread()->tls[entry] = val;
return oldval;
}
#define tls_set(e,v) \
({ \
STATIC_ASSERT((e) < MAX_TLS_ENTRY); \
__tls_set(e, v); \
})
/* thread level statistics */
#if THREAD_STATS
struct thread_stats {
lk_bigtime_t idle_time;
lk_bigtime_t last_idle_timestamp;
ulong reschedules;
ulong context_switches;
ulong preempts;
ulong yields;
ulong interrupts; /* platform code increment this */
ulong timer_ints; /* timer code increment this */
ulong timers; /* timer code increment this */
#if WITH_SMP
ulong reschedule_ipis;
#endif
};
extern struct thread_stats thread_stats[SMP_MAX_CPUS];
#define THREAD_STATS_INC(name) do { thread_stats[arch_curr_cpu_num()].name++; } while(0)
#else
#define THREAD_STATS_INC(name) do { } while (0)
#endif
__END_CDECLS;
#endif
|
import unittest
import numpy as np
import numpy.testing as np_test
import pandas as pd
from pgmpy.models.BayesianModel import BayesianModel
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference.CausalInference import CausalInference
class TestCausalGraphMethods(unittest.TestCase):
def setUp(self):
self.game = BayesianModel(
[("A", "X"), ("A", "B"), ("C", "B"), ("C", "Y"), ("X", "Y"), ("B", "X")]
)
self.inference = CausalInference(self.game)
def test_is_d_separated(self):
self.assertTrue(self.inference.model.is_dconnected("X", "Y", observed=None))
self.assertFalse(
self.inference.model.is_dconnected("B", "Y", observed=("C", "X"))
)
def test_backdoor_validation(self):
self.inference.is_valid_backdoor_adjustment_set("X", "Y", Z="C")
class TestBackdoorPaths(unittest.TestCase):
"""
These tests are drawn from games presented in The Book of Why by Judea Pearl. See the Jupyter Notebook called
Causal Games in the examples folder for further explanation about each of these.
"""
def test_game1(self):
game1 = BayesianModel([("X", "A"), ("A", "Y"), ("A", "B")])
inference = CausalInference(game1)
self.assertTrue(inference.is_valid_backdoor_adjustment_set("X", "Y"))
deconfounders = inference.get_all_backdoor_adjustment_sets("X", "Y")
self.assertEqual(deconfounders, frozenset())
def test_game2(self):
game2 = BayesianModel(
[
("X", "E"),
("E", "Y"),
("A", "B"),
("A", "X"),
("B", "C"),
("D", "B"),
("D", "E"),
]
)
inference = CausalInference(game2)
self.assertTrue(inference.is_valid_backdoor_adjustment_set("X", "Y"))
deconfounders = inference.get_all_backdoor_adjustment_sets("X", "Y")
self.assertEqual(deconfounders, frozenset())
def test_game3(self):
game3 = BayesianModel(
[("X", "Y"), ("X", "A"), ("B", "A"), ("B", "Y"), ("B", "X")]
)
inference = CausalInference(game3)
self.assertFalse(inference.is_valid_backdoor_adjustment_set("X", "Y"))
deconfounders = inference.get_all_backdoor_adjustment_sets("X", "Y")
self.assertEqual(deconfounders, frozenset({frozenset({"B"})}))
def test_game4(self):
game4 = BayesianModel([("A", "X"), ("A", "B"), ("C", "B"), ("C", "Y")])
inference = CausalInference(game4)
self.assertTrue(inference.is_valid_backdoor_adjustment_set("X", "Y"))
deconfounders = inference.get_all_backdoor_adjustment_sets("X", "Y")
self.assertEqual(deconfounders, frozenset())
def test_game5(self):
game5 = BayesianModel(
[("A", "X"), ("A", "B"), ("C", "B"), ("C", "Y"), ("X", "Y"), ("B", "X")]
)
inference = CausalInference(game5)
self.assertFalse(inference.is_valid_backdoor_adjustment_set("X", "Y"))
deconfounders = inference.get_all_backdoor_adjustment_sets("X", "Y")
self.assertEqual(
deconfounders, frozenset({frozenset({"C"}), frozenset({"A", "B"})})
)
def test_game6(self):
game6 = BayesianModel(
[
("X", "F"),
("C", "X"),
("A", "C"),
("A", "D"),
("B", "D"),
("B", "E"),
("D", "X"),
("D", "Y"),
("E", "Y"),
("F", "Y"),
]
)
inference = CausalInference(game6)
self.assertFalse(inference.is_valid_backdoor_adjustment_set("X", "Y"))
deconfounders = inference.get_all_backdoor_adjustment_sets("X", "Y")
self.assertEqual(
deconfounders,
frozenset(
{
frozenset({"C", "D"}),
frozenset({"A", "D"}),
frozenset({"D", "E"}),
frozenset({"B", "D"}),
}
),
)
class TestDoQuery(unittest.TestCase):
def setUp(self):
self.simpson_model = self.get_simpson_model()
self.simp_infer = CausalInference(self.simpson_model)
self.example_model = self.get_example_model()
self.example_infer = CausalInference(self.example_model)
def get_simpson_model(self):
simpson_model = BayesianModel([("S", "T"), ("T", "C"), ("S", "C")])
cpd_s = TabularCPD(
variable="S",
variable_card=2,
values=[[0.5], [0.5]],
state_names={"S": ["m", "f"]},
)
cpd_t = TabularCPD(
variable="T",
variable_card=2,
values=[[0.25, 0.75], [0.75, 0.25]],
evidence=["S"],
evidence_card=[2],
state_names={"S": ["m", "f"], "T": [0, 1]},
)
cpd_c = TabularCPD(
variable="C",
variable_card=2,
values=[[0.3, 0.4, 0.7, 0.8], [0.7, 0.6, 0.3, 0.2]],
evidence=["S", "T"],
evidence_card=[2, 2],
state_names={"S": ["m", "f"], "T": [0, 1], "C": [0, 1]},
)
simpson_model.add_cpds(cpd_s, cpd_t, cpd_c)
return simpson_model
def get_example_model(self):
# Model structure: Z -> X -> Y; Z -> W -> Y
example_model = BayesianModel([("X", "Y"), ("Z", "X"), ("Z", "W"), ("W", "Y")])
cpd_z = TabularCPD(variable="Z", variable_card=2, values=[[0.2], [0.8]])
cpd_x = TabularCPD(
variable="X",
variable_card=2,
values=[[0.1, 0.3], [0.9, 0.7]],
evidence=["Z"],
evidence_card=[2],
)
cpd_w = TabularCPD(
variable="W",
variable_card=2,
values=[[0.2, 0.9], [0.8, 0.1]],
evidence=["Z"],
evidence_card=[2],
)
cpd_y = TabularCPD(
variable="Y",
variable_card=2,
values=[[0.3, 0.4, 0.7, 0.8], [0.7, 0.6, 0.3, 0.2]],
evidence=["X", "W"],
evidence_card=[2, 2],
)
example_model.add_cpds(cpd_z, cpd_x, cpd_w, cpd_y)
return example_model
def test_query(self):
for algo in ["ve", "bp"]:
query_nodo1 = self.simp_infer.query(
variables=["C"], do=None, evidence={"T": 1}, inference_algo=algo
)
np_test.assert_array_almost_equal(query_nodo1.values, np.array([0.5, 0.5]))
query_nodo2 = self.simp_infer.query(
variables=["C"], do=None, evidence={"T": 0}, inference_algo=algo
)
np_test.assert_array_almost_equal(query_nodo2.values, np.array([0.6, 0.4]))
query1 = self.simp_infer.query(
variables=["C"], do={"T": 1}, inference_algo=algo
)
np_test.assert_array_almost_equal(query1.values, np.array([0.6, 0.4]))
query2 = self.simp_infer.query(
variables=["C"], do={"T": 0}, inference_algo=algo
)
np_test.assert_array_almost_equal(query2.values, np.array([0.5, 0.5]))
query3 = self.simp_infer.query(["C"], adjustment_set=["S"])
np_test.assert_array_almost_equal(query3.values, np.array([0.55, 0.45]))
def test_adjustment_query(self):
for algo in ["ve", "bp"]:
# Test adjustment with do operation.
query1 = self.example_infer.query(
variables=["Y"], do={"X": 1}, adjustment_set={"Z"}, inference_algo=algo
)
np_test.assert_array_almost_equal(query1.values, np.array([0.7240, 0.2760]))
query2 = self.example_infer.query(
variables=["Y"], do={"X": 1}, adjustment_set={"W"}, inference_algo=algo
)
np_test.assert_array_almost_equal(query2.values, np.array([0.7240, 0.2760]))
# Test adjustment without do operation.
query3 = self.example_infer.query(["Y"], adjustment_set=["W"])
np_test.assert_array_almost_equal(query3.values, np.array([0.62, 0.38]))
query4 = self.example_infer.query(["Y"], adjustment_set=["Z"])
np_test.assert_array_almost_equal(query4.values, np.array([0.62, 0.38]))
query5 = self.example_infer.query(["Y"], adjustment_set=["W", "Z"])
np_test.assert_array_almost_equal(query5.values, np.array([0.62, 0.38]))
def test_query_error(self):
self.assertRaises(ValueError, self.simp_infer.query, variables="C", do={"T": 1})
self.assertRaises(
ValueError, self.simp_infer.query, variables=["E"], do={"T": 1}
)
self.assertRaises(ValueError, self.simp_infer.query, variables=["C"], do="T")
self.assertRaises(
ValueError,
self.simp_infer.query,
variables=["C"],
do={"T": 1},
evidence="S",
)
self.assertRaises(
ValueError,
self.simp_infer.query,
variables=["C"],
do={"T": 1},
inference_algo="random",
)
class TestEstimator(unittest.TestCase):
def test_create_estimator(self):
game1 = BayesianModel([("X", "A"), ("A", "Y"), ("A", "B")])
data = pd.DataFrame(
np.random.randint(2, size=(1000, 4)), columns=["X", "A", "B", "Y"]
)
inference = CausalInference(model=game1)
ate = inference.estimate_ate("X", "Y", data=data, estimator_type="linear")
self.assertAlmostEqual(ate, 0, places=0)
|
import pprint
from abc import ABC
class Animal(ABC):
def __init__(
self,
color: str,
number_of_legs: int,
**kwargs
) -> None:
self.color = color
self.number_of_legs = number_of_legs
if 'species' in kwargs:
self.species = kwargs['species']
else:
self.species = self.__class__.__name__
def __repr__(
self
) -> str:
return f'{self.color} {self.species}, {self.number_of_legs} legs'
class ZeroLeggedAnimal(Animal):
def __init__(
self,
color: str,
**kwargs
) -> None:
number_of_legs = 0
super().__init__(color, number_of_legs, **kwargs)
class Snake(ZeroLeggedAnimal):
def __init__(
self,
color: str,
**kwargs
) -> None:
super().__init__(color, **kwargs)
def main():
animals = [
Snake('black', species='super_snake'),
]
pprint.pprint(animals)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ... import opcodes as OperandDef
from ...serialize import KeyField
from .core import TensorHasInput
from .array import tensor
class SparseToDense(TensorHasInput):
_op_type_ = OperandDef.SPARSE_TO_DENSE
_input = KeyField('_input')
def __init__(self, dtype=None, gpu=None, **kw):
super(SparseToDense, self).__init__(_dtype=dtype, _gpu=gpu,
_sparse=False, **kw)
@classmethod
def execute(cls, ctx, op):
ctx[op.outputs[0].key] = ctx[op.inputs[0].key].toarray()
def fromsparse(a):
a = tensor(a)
if not a.issparse():
return a
op = SparseToDense(dtype=a.dtype, gpu=a.op.gpu)
return op(a)
|
/***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* SeisComP Public License for more details. *
***************************************************************************/
#ifndef __SEISCOMP_PROCESSING_SENSOR_H__
#define __SEISCOMP_PROCESSING_SENSOR_H__
#include <seiscomp3/core/baseobject.h>
#include <seiscomp3/processing/response.h>
#include <seiscomp3/client.h>
namespace Seiscomp {
namespace Processing {
DEFINE_SMARTPOINTER(Sensor);
class SC_SYSTEM_CLIENT_API Sensor : public Core::BaseObject {
// ----------------------------------------------------------------------
// X'truction
// ----------------------------------------------------------------------
public:
Sensor();
// ----------------------------------------------------------------------
// Public interface
// ----------------------------------------------------------------------
public:
void setModel(const std::string& model);
const std::string& model() const;
void setManufacturer(const std::string& manufacturer);
const std::string& manufacturer() const;
void setType(const std::string& type);
const std::string& type() const;
void setUnit(const std::string& unit);
const std::string& unit() const;
void setLowFrequency(const OPT(double)& lowFrequency);
double lowFrequency() const throw(Seiscomp::Core::ValueException);
void setHighFrequency(const OPT(double)& highFrequency);
double highFrequency() const throw(Seiscomp::Core::ValueException);
Response *response() const;
void setResponse(Response *response);
// ----------------------------------------------------------------------
// Members
// ----------------------------------------------------------------------
private:
ResponsePtr _response;
std::string _model;
std::string _manufacturer;
std::string _type;
std::string _unit;
OPT(double) _lowFrequency;
OPT(double) _highFrequency;
};
}
}
#endif
|
'use strict';
/**
* Management of a device. Supports quering it for information and changing
* the WiFi settings.
*/
class DeviceManagement {
constructor(device) {
this.device = device;
}
/**
* Get information about this device. Includes model info, token and
* connection information.
*/
info() {
return this.device.call('miIO.info');
}
/**
* Update the wireless settings of this device. Needs `ssid` and `passwd`
* to be set in the options object.
*
* `uid` can be set to associate the device with a Mi Home user id.
*/
updateWireless(options) {
if(typeof options.ssid !== 'string') {
throw new Error('options.ssid must be a string');
}
if(typeof options.passwd !== 'string') {
throw new Error('options.passwd must be a string');
}
return this.device.call('miIO.config_router', options)
.then(result => {
if(result !== 0 && result !== 'OK' && result !== 'ok') {
throw new Error('Failed updating wireless');
}
return true;
});
}
/**
* Get the wireless state of this device. Includes if the device is
* online and counters for things such as authentication failures and
* connection success and failures.
*/
wirelessState() {
return this.device.call('miIO.wifi_assoc_state');
}
}
module.exports = DeviceManagement;
|
"""
The MIT License (MIT)
Copyright (c) 2021 Losant IoT, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import json
""" Module for Losant API Experience wrapper class """
# pylint: disable=C0301
class Experience(object):
""" Class containing all the actions for the Experience Resource """
def __init__(self, client):
self.client = client
def bootstrap(self, **kwargs):
"""
Bootstraps the experience for this application with standard endpoints and views
Authentication:
The client must be configured with a valid api
access token to call this action. The token
must include at least one of the following scopes:
all.Application, all.Application.cli, all.Organization, all.User, all.User.cli, experience.*, or experience.bootstrap.
Parameters:
* {string} applicationId - ID associated with the application
* {hash} options - Bootstrap options (https://api.losant.com/#/definitions/experienceBootstrapOptions)
* {string} losantdomain - Domain scope of request (rarely needed)
* {boolean} _actions - Return resource actions in response
* {boolean} _links - Return resource link in response
* {boolean} _embedded - Return embedded resources in response
Responses:
* 200 - If bootstrap was successful (https://api.losant.com/#/definitions/experienceBootstrapResult)
Errors:
* 400 - Error if malformed request (https://api.losant.com/#/definitions/error)
* 404 - Error if application was not found (https://api.losant.com/#/definitions/error)
"""
query_params = {"_actions": "false", "_links": "true", "_embedded": "true"}
path_params = {}
headers = {}
body = None
if "applicationId" in kwargs:
path_params["applicationId"] = kwargs["applicationId"]
if "options" in kwargs:
body = kwargs["options"]
if "losantdomain" in kwargs:
headers["losantdomain"] = kwargs["losantdomain"]
if "_actions" in kwargs:
query_params["_actions"] = kwargs["_actions"]
if "_links" in kwargs:
query_params["_links"] = kwargs["_links"]
if "_embedded" in kwargs:
query_params["_embedded"] = kwargs["_embedded"]
path = "/applications/{applicationId}/experience/bootstrap".format(**path_params)
return self.client.request("PATCH", path, params=query_params, headers=headers, body=body)
def delete(self, **kwargs):
"""
Deletes multiple parts of an experience including users, groups, slugs, domains, versions, endpoints, views, and workflows
Authentication:
The client must be configured with a valid api
access token to call this action. The token
must include at least one of the following scopes:
all.Application, all.Organization, all.User, experience.*, or experience.delete.
Parameters:
* {string} applicationId - ID associated with the application
* {string} keepUsers - If this is set, Experience Users will not be removed.
* {string} keepGroups - If this is set, Experience Groups will not be removed.
* {string} keepSlugs - If this is set, Experience Slugs will not be removed.
* {string} keepDomains - If this is set, Experience Domains will not be removed.
* {string} removeVersions - If this is set, all Experience Versions and their contents will be removed (except for develop).
* {string} keepViews - If this is set, Experience Views (in the develop version) will not be removed.
* {string} keepEndpoints - If this is set, Experience Endpoints (in the develop version) will not be removed.
* {string} removeWorkflows - If this is set, all Experience Workflows (in the develop version) will ve removed.
* {string} losantdomain - Domain scope of request (rarely needed)
* {boolean} _actions - Return resource actions in response
* {boolean} _links - Return resource link in response
* {boolean} _embedded - Return embedded resources in response
Responses:
* 200 - If deletion was successful (https://api.losant.com/#/definitions/success)
Errors:
* 400 - Error if malformed request (https://api.losant.com/#/definitions/error)
* 404 - Error if application was not found (https://api.losant.com/#/definitions/error)
"""
query_params = {"_actions": "false", "_links": "true", "_embedded": "true"}
path_params = {}
headers = {}
body = None
if "applicationId" in kwargs:
path_params["applicationId"] = kwargs["applicationId"]
if "keepUsers" in kwargs:
query_params["keepUsers"] = kwargs["keepUsers"]
if "keepGroups" in kwargs:
query_params["keepGroups"] = kwargs["keepGroups"]
if "keepSlugs" in kwargs:
query_params["keepSlugs"] = kwargs["keepSlugs"]
if "keepDomains" in kwargs:
query_params["keepDomains"] = kwargs["keepDomains"]
if "removeVersions" in kwargs:
query_params["removeVersions"] = kwargs["removeVersions"]
if "keepViews" in kwargs:
query_params["keepViews"] = kwargs["keepViews"]
if "keepEndpoints" in kwargs:
query_params["keepEndpoints"] = kwargs["keepEndpoints"]
if "removeWorkflows" in kwargs:
query_params["removeWorkflows"] = kwargs["removeWorkflows"]
if "losantdomain" in kwargs:
headers["losantdomain"] = kwargs["losantdomain"]
if "_actions" in kwargs:
query_params["_actions"] = kwargs["_actions"]
if "_links" in kwargs:
query_params["_links"] = kwargs["_links"]
if "_embedded" in kwargs:
query_params["_embedded"] = kwargs["_embedded"]
path = "/applications/{applicationId}/experience".format(**path_params)
return self.client.request("DELETE", path, params=query_params, headers=headers, body=body)
|
(function JVM_net_nexustools_jvm_bridge_JSObjectRef_Controller($JVM, JVM){
$JVM.ClassLoader.defineClass("net/nexustools/jvm/bridge/JSObjectRef$Controller", [], "java/lang/Object", [
{
"type": "method",
"name": "getRef",
"signature": "()Lnet/nexustools/jvm/bridge/JSObjectRef;",
"sigparts": {
"return": "Lnet/nexustools/jvm/bridge/JSObjectRef;",
"args": []
},
"implementation": [
{
"type": "end"
}
],
"access": [
JVM.Flags.ABSTRACT,
JVM.Flags.PUBLIC
]
},
{
"type": "references",
"value": [
"java/lang/Object",
"net/nexustools/jvm/bridge/JSObjectRef"
]
}
]);
})($currentJVM, JVM);
|
"""\
basis_6311pp_1d_1p.dat basis set for use with PyQuante (added by Globulion - from GAUSSIAN09 log file)
This program is part of the PyQuante quantum chemistry program suite.
Copyright (c) 2004, Richard P. Muller. All Rights Reserved.
PyQuante version 1.2 and later is covered by the modified BSD
license. Please see the file LICENSE that is part of this
distribution.
Basis: 6-311++G**
ELEMENTS: H, C, N, O, Na, S, Cl
"""
basis_data = \
{1: [('S',
# HYDROGENIUM
[(33.865000000000002, 0.02549381454),
(5.0947899999999997, 0.1903731086),
(1.15879, 0.8521614860)]),
('S', [(0.32584000000000002, 1.0)]),
('S', [(0.102741, 1.0)]),
('S', [(0.0360, 1.0)]),
('P', [(0.75, 1.0)])],
# LITHIUM
3: [('S',
[(0.9004600000E+03 , 0.2287040374E-02),
(0.1344330000E+03 , 0.1763500289E-01),
(0.3043650000E+02 , 0.8734341430E-01),
(0.8626390000E+01 , 0.2809770460E+00),
(0.2483320000E+01 , 0.6587411078E+00),
(0.3031790000E+00 , 0.1187120194E+00)]),
('S',
[(0.4868900000E+01 , 0.9332929951E-01),
(0.8569240000E+00 , 0.9430449951E+00),
(0.2432270000E+00 ,-0.2798269985E-02)]),
('P',
[(0.4868900000E+01 , 0.3276609658E-01),
(0.8569240000E+00 , 0.1597919833E+00),
(0.2432270000E+00 , 0.8856669076E+00)]),
('S',
[(0.6350700000E-01 , 0.1000000000E+01)]),
('P',
[(0.6350700000E-01 , 0.1000000000E+01)]),
('S',
[(0.2436830000E-01 , 0.1000000000E+01)]),
('P',
[(0.2436830000E-01 , 0.1000000000E+01)]),
('S',
[(0.7400000000E-02 , 0.1000000000E+01)]),
('P',
[(0.7400000000E-02 , 0.1000000000E+01)]),
('D',
[(0.2000000000E+00 , 0.1000000000E+01)])],
# CARBONIUM
6: [('S',
[(4563.2399999999998, 0.001966650249),
(682.024, 0.01523060193),
(154.97300000000001, 0.07612690966),
(44.455300000000001, 0.2608010331),
(13.029, 0.6164620782),
(1.8277300000000001, 0.2210060280)]),
('S',
[(20.964200000000002, 0.1146600807),
(4.8033099999999997, 0.9199996477),
(1.45933, -0.003030682134)]),
('P',
[(20.964200000000002, 0.04024869267),
(4.8033099999999997, 0.2375939567),
(1.45933, 0.8158538515)]),
('S', [(0.483456, 1.0)]),
('P', [(0.483456, 1.0)]),
('S', [(0.14558499999999999, 1.0)]),
('P', [(0.14558499999999999, 1.0)]),
('S', [(0.043799999999999999, 1.0)]),
('P', [(0.043799999999999999, 1.0)]),
('D', [(0.626, 1.0)])],
# NITROGENIUM
7: [('S',
[(6293.4799999999996, 0.001969788147),
(949.04399999999998, 0.01496128592),
(218.77600000000001, 0.07350053084),
(63.691600000000001, 0.2489367658),
(18.828199999999999, 0.6024594331),
(2.7202299999999999, 0.2562017589)]),
('S',
[(30.633099999999999, 0.1119060795),
(7.0261399999999998, 0.9216666549),
(2.11205, -0.002569191826)]),
('P',
[(30.633099999999999, 0.03831191864),
(7.0261399999999998, 0.2374031155),
(2.11205, 0.8175923978)]),
('S', [(0.68400899999999998, 1.0)]),
('P', [(0.68400899999999998, 1.0)]),
('S', [(0.200878, 1.0)]),
('P', [(0.200878, 1.0)]),
('S', [(0.063899999999999998, 1.0)]),
('P', [(0.063899999999999998, 1.0)]),
('D', [(0.91300000000000003, 1.0)])],
# OXYGENIUM
8: [('S',
[(8588.5, 0.001895150083),
(1297.23, 0.01438590064),
(299.29599999999999, 0.07073200310),
(87.377099999999999, 0.24000101050),
(25.678899999999999, 0.59479702610),
(3.74004, 0.2808020123)]),
('S',
[(42.1175, 0.1138890124),
(9.6283700000000003, 0.9208111006),
(2.8533200000000001, -0.003274470358)]),
('P',
[(42.1175, 0.03651139738),
(9.6283700000000003, 0.2371529830),
(2.8533200000000001, 0.8197019412)]),
('S', [(0.90566100000000005, 1.0)]),
('P', [(0.90566100000000005, 1.0)]),
('S', [(0.25561099999999998, 1.0)]),
('P', [(0.25561099999999998, 1.0)]),
('S', [(0.084500000000000006, 1.0)]),
('P', [(0.084500000000000006, 1.0)]),
('D', [(1.292, 1.0)])],
# FLUORIUM
9: [('S',
[(11427.10000, 0.001800930156),
(1722.350000, 0.01374190119),
(395.7460000, 0.06813340591),
(115.1390000, 0.2333250202),
(33.60260000, 0.5890860511),
(4.919010000, 0.2995050260)]),
('S',
[(55.44410000, 0.1145360155),
(12.63230000, 0.9205121249),
(3.717560000,-0.003378040458)]),
('P',
[(55.44410000, 0.03546088738),
(12.63230000, 0.2374509155),
(3.717560000, 0.8204577080)]),
('S', [(1.165450000, 1.0)]),
('P', [(1.165450000, 1.0)]),
('S', [(0.321892000, 1.0)]),
('P', [(0.321892000, 1.0)]),
('S', [(0.107600000, 1.0)]),
('P', [(0.107600000, 1.0)]),
('D', [(1.750000000, 1.0)])],
# NATRIUM
11: [('S',
[(36166.400000000001, 0.0010319999999999999),
(5372.5799999999999, 0.008071003557),
(1213.21, 0.04212901857),
(339.62299999999999, 0.1697890748),
(109.553, 0.5146212268),
(38.777299999999997, 0.3798171674)]),
('S',
[(38.777299999999997, 0.3747618096),
(14.575900000000001, 0.5757687076),
(5.2699299999999996, 0.1129329426)]),
('S', [(1.8277699999999999, 1.0)]),
('S', [(0.61994800000000005, 1.0)]),
('S', [(0.057239999999999999, 1.0)]),
('S', [(0.024048, 1.0)]),
('S', [(0.007600000,1.0)]),
('P', [(0.007600000,1.0)]),
('P',
[(144.64500000000001, 0.01148500160),
(33.907400000000003, 0.08238301148),
(10.628500000000001, 0.3196580445),
(3.82389, 0.7012950977)]),
('P',
[(1.4442900000000001, 0.6385061213),
(0.55262100000000003, 0.4253650808)]),
('P', [(0.18872, 1.0)]),
('P', [(0.046501000000000001, 1.0)]),
('P', [(0.016285000000000001, 1.0)]),
('D', [(0.175000, 1.0)])],
# SULPHUR
16: [('S',
[(93413.4, 0.0007429999567),
(13961.7, 0.005792999662),
(3169.91, 0.02995399825),
(902.456, 0.1190279931),
(297.158, 0.3684319785),
(108.702, 0.5772989663)]),
('S',
[(108.702, 0.1431860600),
(43.1553, 0.6244652619),
(18.1079, 0.2833661188)]),
('S', [(5.560090000, 1.0)]),
('S', [(2.131830000, 1.0)]),
('S', [(0.420403000, 1.0)]),
('S', [(0.136045000, 1.0)]),
('S', [(0.040500000, 1.0)]),
('P', [(0.040500000, 1.0)]),
('P',
[(495.040, 0.008309002531),
(117.221, 0.06402401937),
(37.7749, 0.2776140840),
(14.0584, 0.7450762254)]),
('P',
[(5.56574, 0.6137116720),
(2.26297, 0.4438177628)]),
('P', [(0.807994, 1.0)]),
('P', [(0.277460, 1.0)]),
('P', [(0.077141, 1.0)]),
('D', [(0.650000, 1.0)]) ],
# CHLORIUM
17: [('S',
[(105819.0, 0.0007380002465),
(15872.0 , 0.005718001910),
(3619.65 , 0.02949500985),
(1030.8 , 0.1172860392),
(339.908 , 0.3629491212),
(124.538 , 0.5841491951)]),
('S',
[(124.538, 0.1341769734),
(49.5135, 0.6242498762),
(20.8056, 0.2917559421)]),
('S', [(6.58346 , 1.0)]),
('S', [(2.56468 , 1.0)]),
('S', [(0.559763, 1.0)]),
('S', [(0.183273, 1.0)]),
('S', [(0.0483, 1.0)]),
('P', [(0.0483, 1.0)]),
('P',
[(589.776 , 0.003665569355),
(139.849 , 0.02836791942),
(45.1413 , 0.1247566028),
(16.8733 , 0.3396546305),
(2.77152 , 0.7475859630)]), # different than it was previously
('P',
[(6.7411 ,-1.572243813),
(2.77152 , 0.9923888817)]),
('P', [(1.02387 , 1.0)]),
('P', [(0.381368, 1.0)]),
('P', [(0.109437, 1.0)]),
('D', [(0.75, 1.0)])],
}
|
import tensorflow as tf
class StateProcessor(object):
"""
Processes a raw Atari iamges. Resizes it and converts it to grayscale.
# D. Britz Implementation
"""
def __init__(self):
# Build the Tensorflow graph
with tf.variable_scope("state_processor"):
self.input_state = tf.placeholder(
shape=[210, 160, 3], dtype=tf.uint8)
self.output = tf.image.rgb_to_grayscale(self.input_state)
self.output = tf.image.crop_to_bounding_box(
self.output, 34, 0, 160, 160)
self.output = tf.image.resize_images(
self.output, (84, 84),
method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
self.output = tf.squeeze(self.output)
def process(self, sess, state):
"""
Args:
sess: A Tensorflow session object
state: A [210, 160, 3] Atari RGB State
Returns:
A processed [84, 84, 1] state representing grayscale values.
"""
return sess.run(self.output, feed_dict={self.input_state: state})
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/VectorKit.framework/Versions/A/VectorKit
*/
@interface VKPShieldIndex : PBCodable <NSCopying> {
NSMutableArray * _entries;
NSMutableArray * _textEntries;
NSMutableArray * _variantEntries;
}
@property (nonatomic, readwrite, retain) NSMutableArray *entries;
@property (nonatomic, readwrite, retain) NSMutableArray *textEntries;
@property (nonatomic, readwrite, retain) NSMutableArray *variantEntries;
- (void)addEntries:(id)arg1;
- (void)addTextEntries:(id)arg1;
- (void)addVariantEntries:(id)arg1;
- (void)clearEntries;
- (void)clearTextEntries;
- (void)clearVariantEntries;
- (void)copyTo:(id)arg1;
- (id)copyWithZone:(struct _NSZone { }*)arg1;
- (void)dealloc;
- (id)description;
- (id)dictionaryRepresentation;
- (id)entries;
- (id)entriesAtIndex:(unsigned long long)arg1;
- (unsigned long long)entriesCount;
- (unsigned long long)hash;
- (BOOL)isEqual:(id)arg1;
- (void)mergeFrom:(id)arg1;
- (BOOL)readFrom:(id)arg1;
- (void)setEntries:(id)arg1;
- (void)setTextEntries:(id)arg1;
- (void)setVariantEntries:(id)arg1;
- (id)textEntries;
- (id)textEntriesAtIndex:(unsigned long long)arg1;
- (unsigned long long)textEntriesCount;
- (id)variantEntries;
- (id)variantEntriesAtIndex:(unsigned long long)arg1;
- (unsigned long long)variantEntriesCount;
- (void)writeTo:(id)arg1;
// VKPShieldIndex (VKShieldManagerAdditions)
- (id)artworkIdentifierForShieldType:(long long)arg1 textSpecificIdentifiers:(id*)arg2 variant:(unsigned long long)arg3;
- (id)defaultArtworkIdentifierForFeatureType:(int)arg1 variant:(unsigned long long)arg2;
@end
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import outputs
from ._inputs import *
__all__ = ['PubicCloudPrivateNetworkArgs', 'PubicCloudPrivateNetwork']
@pulumi.input_type
class PubicCloudPrivateNetworkArgs:
def __init__(__self__, *,
project_id: pulumi.Input[str],
name: Optional[pulumi.Input[str]] = None,
regions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
vlan_id: Optional[pulumi.Input[int]] = None):
"""
The set of arguments for constructing a PubicCloudPrivateNetwork resource.
:param pulumi.Input[str] project_id: The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
:param pulumi.Input[str] name: The name of the network.
:param pulumi.Input[Sequence[pulumi.Input[str]]] regions: an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
:param pulumi.Input[int] vlan_id: a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
pulumi.set(__self__, "project_id", project_id)
if name is not None:
pulumi.set(__self__, "name", name)
if regions is not None:
pulumi.set(__self__, "regions", regions)
if vlan_id is not None:
pulumi.set(__self__, "vlan_id", vlan_id)
@property
@pulumi.getter(name="projectId")
def project_id(self) -> pulumi.Input[str]:
"""
The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
"""
return pulumi.get(self, "project_id")
@project_id.setter
def project_id(self, value: pulumi.Input[str]):
pulumi.set(self, "project_id", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the network.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def regions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
"""
return pulumi.get(self, "regions")
@regions.setter
def regions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "regions", value)
@property
@pulumi.getter(name="vlanId")
def vlan_id(self) -> Optional[pulumi.Input[int]]:
"""
a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
return pulumi.get(self, "vlan_id")
@vlan_id.setter
def vlan_id(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "vlan_id", value)
@pulumi.input_type
class _PubicCloudPrivateNetworkState:
def __init__(__self__, *,
name: Optional[pulumi.Input[str]] = None,
project_id: Optional[pulumi.Input[str]] = None,
regions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
regions_statuses: Optional[pulumi.Input[Sequence[pulumi.Input['PubicCloudPrivateNetworkRegionsStatusArgs']]]] = None,
status: Optional[pulumi.Input[str]] = None,
type: Optional[pulumi.Input[str]] = None,
vlan_id: Optional[pulumi.Input[int]] = None):
"""
Input properties used for looking up and filtering PubicCloudPrivateNetwork resources.
:param pulumi.Input[str] name: The name of the network.
:param pulumi.Input[str] project_id: The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
:param pulumi.Input[Sequence[pulumi.Input[str]]] regions: an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
:param pulumi.Input[Sequence[pulumi.Input['PubicCloudPrivateNetworkRegionsStatusArgs']]] regions_statuses: A map representing the status of the network per region.
* `regions_status/region` - The id of the region.
* `regions_status/status` - The status of the network in the region.
:param pulumi.Input[str] status: the status of the network. should be normally set to 'ACTIVE'.
:param pulumi.Input[str] type: the type of the network. Either 'private' or 'public'.
:param pulumi.Input[int] vlan_id: a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
if name is not None:
pulumi.set(__self__, "name", name)
if project_id is not None:
pulumi.set(__self__, "project_id", project_id)
if regions is not None:
pulumi.set(__self__, "regions", regions)
if regions_statuses is not None:
pulumi.set(__self__, "regions_statuses", regions_statuses)
if status is not None:
pulumi.set(__self__, "status", status)
if type is not None:
pulumi.set(__self__, "type", type)
if vlan_id is not None:
pulumi.set(__self__, "vlan_id", vlan_id)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the network.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="projectId")
def project_id(self) -> Optional[pulumi.Input[str]]:
"""
The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
"""
return pulumi.get(self, "project_id")
@project_id.setter
def project_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "project_id", value)
@property
@pulumi.getter
def regions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
"""
return pulumi.get(self, "regions")
@regions.setter
def regions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "regions", value)
@property
@pulumi.getter(name="regionsStatuses")
def regions_statuses(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['PubicCloudPrivateNetworkRegionsStatusArgs']]]]:
"""
A map representing the status of the network per region.
* `regions_status/region` - The id of the region.
* `regions_status/status` - The status of the network in the region.
"""
return pulumi.get(self, "regions_statuses")
@regions_statuses.setter
def regions_statuses(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['PubicCloudPrivateNetworkRegionsStatusArgs']]]]):
pulumi.set(self, "regions_statuses", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[str]]:
"""
the status of the network. should be normally set to 'ACTIVE'.
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "status", value)
@property
@pulumi.getter
def type(self) -> Optional[pulumi.Input[str]]:
"""
the type of the network. Either 'private' or 'public'.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "type", value)
@property
@pulumi.getter(name="vlanId")
def vlan_id(self) -> Optional[pulumi.Input[int]]:
"""
a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
return pulumi.get(self, "vlan_id")
@vlan_id.setter
def vlan_id(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "vlan_id", value)
class PubicCloudPrivateNetwork(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
name: Optional[pulumi.Input[str]] = None,
project_id: Optional[pulumi.Input[str]] = None,
regions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
vlan_id: Optional[pulumi.Input[int]] = None,
__props__=None):
"""
> __DEPRECATED:__ Use `CloudNetworkPrivate` instead.
Creates a private network in a public cloud project.
## Example Usage
```python
import pulumi
import pulumi_ovh as ovh
net = ovh.PubicCloudPrivateNetwork("net",
project_id="67890",
regions=[
"GRA1",
"BHS1",
])
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] name: The name of the network.
:param pulumi.Input[str] project_id: The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
:param pulumi.Input[Sequence[pulumi.Input[str]]] regions: an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
:param pulumi.Input[int] vlan_id: a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: PubicCloudPrivateNetworkArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
> __DEPRECATED:__ Use `CloudNetworkPrivate` instead.
Creates a private network in a public cloud project.
## Example Usage
```python
import pulumi
import pulumi_ovh as ovh
net = ovh.PubicCloudPrivateNetwork("net",
project_id="67890",
regions=[
"GRA1",
"BHS1",
])
```
:param str resource_name: The name of the resource.
:param PubicCloudPrivateNetworkArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(PubicCloudPrivateNetworkArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
name: Optional[pulumi.Input[str]] = None,
project_id: Optional[pulumi.Input[str]] = None,
regions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
vlan_id: Optional[pulumi.Input[int]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = PubicCloudPrivateNetworkArgs.__new__(PubicCloudPrivateNetworkArgs)
__props__.__dict__["name"] = name
if project_id is None and not opts.urn:
raise TypeError("Missing required property 'project_id'")
__props__.__dict__["project_id"] = project_id
__props__.__dict__["regions"] = regions
__props__.__dict__["vlan_id"] = vlan_id
__props__.__dict__["regions_statuses"] = None
__props__.__dict__["status"] = None
__props__.__dict__["type"] = None
super(PubicCloudPrivateNetwork, __self__).__init__(
'ovh:index/pubicCloudPrivateNetwork:PubicCloudPrivateNetwork',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
name: Optional[pulumi.Input[str]] = None,
project_id: Optional[pulumi.Input[str]] = None,
regions: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
regions_statuses: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PubicCloudPrivateNetworkRegionsStatusArgs']]]]] = None,
status: Optional[pulumi.Input[str]] = None,
type: Optional[pulumi.Input[str]] = None,
vlan_id: Optional[pulumi.Input[int]] = None) -> 'PubicCloudPrivateNetwork':
"""
Get an existing PubicCloudPrivateNetwork resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] name: The name of the network.
:param pulumi.Input[str] project_id: The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
:param pulumi.Input[Sequence[pulumi.Input[str]]] regions: an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['PubicCloudPrivateNetworkRegionsStatusArgs']]]] regions_statuses: A map representing the status of the network per region.
* `regions_status/region` - The id of the region.
* `regions_status/status` - The status of the network in the region.
:param pulumi.Input[str] status: the status of the network. should be normally set to 'ACTIVE'.
:param pulumi.Input[str] type: the type of the network. Either 'private' or 'public'.
:param pulumi.Input[int] vlan_id: a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _PubicCloudPrivateNetworkState.__new__(_PubicCloudPrivateNetworkState)
__props__.__dict__["name"] = name
__props__.__dict__["project_id"] = project_id
__props__.__dict__["regions"] = regions
__props__.__dict__["regions_statuses"] = regions_statuses
__props__.__dict__["status"] = status
__props__.__dict__["type"] = type
__props__.__dict__["vlan_id"] = vlan_id
return PubicCloudPrivateNetwork(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The name of the network.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="projectId")
def project_id(self) -> pulumi.Output[str]:
"""
The id of the public cloud project. If omitted,
the `OVH_PROJECT_ID` environment variable is used.
"""
return pulumi.get(self, "project_id")
@property
@pulumi.getter
def regions(self) -> pulumi.Output[Sequence[str]]:
"""
an array of valid OVH public cloud region ID in which the network
will be available. Ex.: "GRA1". Defaults to all public cloud regions.
"""
return pulumi.get(self, "regions")
@property
@pulumi.getter(name="regionsStatuses")
def regions_statuses(self) -> pulumi.Output[Sequence['outputs.PubicCloudPrivateNetworkRegionsStatus']]:
"""
A map representing the status of the network per region.
* `regions_status/region` - The id of the region.
* `regions_status/status` - The status of the network in the region.
"""
return pulumi.get(self, "regions_statuses")
@property
@pulumi.getter
def status(self) -> pulumi.Output[str]:
"""
the status of the network. should be normally set to 'ACTIVE'.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
the type of the network. Either 'private' or 'public'.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="vlanId")
def vlan_id(self) -> pulumi.Output[Optional[int]]:
"""
a vlan id to associate with the network.
Changing this value recreates the resource. Defaults to 0.
"""
return pulumi.get(self, "vlan_id")
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Pass manager for optimization level 1, providing light optimization.
Level 1 pass manager: light optimization by simple adjacent gate collapsing.
"""
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.passes import Unroller
from qiskit.transpiler.passes import BasisTranslator
from qiskit.transpiler.passes import UnrollCustomDefinitions
from qiskit.transpiler.passes import Unroll3qOrMore
from qiskit.transpiler.passes import CXCancellation
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler.passes import GateDirection
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import DenseLayout
from qiskit.transpiler.passes import NoiseAdaptiveLayout
from qiskit.transpiler.passes import SabreLayout
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler.passes import LookaheadSwap
from qiskit.transpiler.passes import StochasticSwap
from qiskit.transpiler.passes import SabreSwap
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import FixedPoint
from qiskit.transpiler.passes import Depth
from qiskit.transpiler.passes import RemoveResetInZeroState
from qiskit.transpiler.passes import Optimize1qGatesDecomposition
from qiskit.transpiler.passes import ApplyLayout
from qiskit.transpiler.passes import CheckGateDirection
from qiskit.transpiler.passes import Layout2qDistance
from qiskit.transpiler.passes import Collect2qBlocks
from qiskit.transpiler.passes import ConsolidateBlocks
from qiskit.transpiler.passes import UnitarySynthesis
from qiskit.transpiler.passes import TimeUnitConversion
from qiskit.transpiler.passes import ALAPSchedule
from qiskit.transpiler.passes import ASAPSchedule
from qiskit.transpiler.passes import Error
from qiskit.transpiler import TranspilerError
def level_1_pass_manager(pass_manager_config: PassManagerConfig) -> PassManager:
"""Level 1 pass manager: light optimization by simple adjacent gate collapsing.
This pass manager applies the user-given initial layout. If none is given,
and a trivial layout (i-th virtual -> i-th physical) makes the circuit fit
the coupling map, that is used.
Otherwise, the circuit is mapped to the most densely connected coupling subgraph,
and swaps are inserted to map. Any unused physical qubit is allocated as ancilla space.
The pass manager then unrolls the circuit to the desired basis, and transforms the
circuit to match the coupling map. Finally, optimizations in the form of adjacent
gate collapse and redundant reset removal are performed.
Note:
In simulators where ``coupling_map=None``, only the unrolling and
optimization stages are done.
Args:
pass_manager_config: configuration of the pass manager.
Returns:
a level 1 pass manager.
Raises:
TranspilerError: if the passmanager config is invalid.
"""
basis_gates = pass_manager_config.basis_gates
coupling_map = pass_manager_config.coupling_map
initial_layout = pass_manager_config.initial_layout
layout_method = pass_manager_config.layout_method or "dense"
routing_method = pass_manager_config.routing_method or "stochastic"
translation_method = pass_manager_config.translation_method or "translator"
scheduling_method = pass_manager_config.scheduling_method
instruction_durations = pass_manager_config.instruction_durations
seed_transpiler = pass_manager_config.seed_transpiler
backend_properties = pass_manager_config.backend_properties
approximation_degree = pass_manager_config.approximation_degree
# 1. Use trivial layout if no layout given
_given_layout = SetLayout(initial_layout)
_choose_layout_and_score = [
TrivialLayout(coupling_map),
Layout2qDistance(coupling_map, property_name="trivial_layout_score"),
]
def _choose_layout_condition(property_set):
return not property_set["layout"]
# 2. Use a better layout on densely connected qubits, if circuit needs swaps
if layout_method == "trivial":
_improve_layout = TrivialLayout(coupling_map)
elif layout_method == "dense":
_improve_layout = DenseLayout(coupling_map, backend_properties)
elif layout_method == "noise_adaptive":
_improve_layout = NoiseAdaptiveLayout(backend_properties)
elif layout_method == "sabre":
_improve_layout = SabreLayout(coupling_map, max_iterations=2, seed=seed_transpiler)
else:
raise TranspilerError("Invalid layout method %s." % layout_method)
def _not_perfect_yet(property_set):
return (
property_set["trivial_layout_score"] is not None
and property_set["trivial_layout_score"] != 0
)
# 3. Extend dag/layout with ancillas using the full coupling map
_embed = [FullAncillaAllocation(coupling_map), EnlargeWithAncilla(), ApplyLayout()]
# 4. Decompose so only 1-qubit and 2-qubit gates remain
_unroll3q = Unroll3qOrMore()
# 5. Swap to fit the coupling map
_swap_check = CheckMap(coupling_map)
def _swap_condition(property_set):
return not property_set["is_swap_mapped"]
_swap = [BarrierBeforeFinalMeasurements()]
if routing_method == "basic":
_swap += [BasicSwap(coupling_map)]
elif routing_method == "stochastic":
_swap += [StochasticSwap(coupling_map, trials=20, seed=seed_transpiler)]
elif routing_method == "lookahead":
_swap += [LookaheadSwap(coupling_map, search_depth=4, search_width=4)]
elif routing_method == "sabre":
_swap += [SabreSwap(coupling_map, heuristic="lookahead", seed=seed_transpiler)]
elif routing_method == "none":
_swap += [
Error(
msg="No routing method selected, but circuit is not routed to device. "
"CheckMap Error: {check_map_msg}",
action="raise",
)
]
else:
raise TranspilerError("Invalid routing method %s." % routing_method)
# 6. Unroll to the basis
if translation_method == "unroller":
_unroll = [Unroller(basis_gates)]
elif translation_method == "translator":
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel
_unroll = [UnrollCustomDefinitions(sel, basis_gates), BasisTranslator(sel, basis_gates)]
elif translation_method == "synthesis":
_unroll = [
Unroll3qOrMore(),
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=basis_gates),
UnitarySynthesis(basis_gates, approximation_degree=approximation_degree),
]
else:
raise TranspilerError("Invalid translation method %s." % translation_method)
# 7. Fix any bad CX directions
_direction_check = [CheckGateDirection(coupling_map)]
def _direction_condition(property_set):
return not property_set["is_direction_mapped"]
_direction = [GateDirection(coupling_map)]
# 8. Remove zero-state reset
_reset = RemoveResetInZeroState()
# 9. Merge 1q rotations and cancel CNOT gates iteratively until no more change in depth
_depth_check = [Depth(), FixedPoint("depth")]
def _opt_control(property_set):
return not property_set["depth_fixed_point"]
_opt = [Optimize1qGatesDecomposition(basis_gates), CXCancellation()]
# 10. Unify all durations (either SI, or convert to dt if known)
# Schedule the circuit only when scheduling_method is supplied
_scheduling = [TimeUnitConversion(instruction_durations)]
if scheduling_method:
if scheduling_method in {"alap", "as_late_as_possible"}:
_scheduling += [ALAPSchedule(instruction_durations)]
elif scheduling_method in {"asap", "as_soon_as_possible"}:
_scheduling += [ASAPSchedule(instruction_durations)]
else:
raise TranspilerError("Invalid scheduling method %s." % scheduling_method)
# Build pass manager
pm1 = PassManager()
if coupling_map or initial_layout:
pm1.append(_given_layout)
pm1.append(_choose_layout_and_score, condition=_choose_layout_condition)
pm1.append(_improve_layout, condition=_not_perfect_yet)
pm1.append(_embed)
pm1.append(_unroll3q)
pm1.append(_swap_check)
pm1.append(_swap, condition=_swap_condition)
pm1.append(_unroll)
if coupling_map and not coupling_map.is_symmetric:
pm1.append(_direction_check)
pm1.append(_direction, condition=_direction_condition)
pm1.append(_reset)
pm1.append(_depth_check + _opt + _unroll, do_while=_opt_control)
pm1.append(_scheduling)
return pm1
|
"""Wrapper for lifecycle/ak, to be installed by poetry"""
from os import system
from pathlib import Path
from sys import argv
def main():
"""Wrapper around ak bash script"""
current_path = Path(__file__)
args = " ".join(argv[1:])
system(f"{current_path.parent}/ak {args}") # nosec
if __name__ == "__main__":
main()
|
# Copyright (c) 2010-2021 Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2010-2016, Neotion
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#pylint: disable-msg=missing-docstring
__version__ = '0.53.0'
__title__ = 'PyFtdi'
__description__ = 'FTDI device driver (pure Python)'
__uri__ = 'http://github.com/eblot/pyftdi'
__doc__ = __description__ + ' <' + __uri__ + '>'
__author__ = 'Emmanuel Blot'
# For all support requests, please open a new issue on GitHub
__email__ = 'emmanuel.blot@free.fr'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright (c) 2011-2021 Emmanuel Blot'
from logging import WARNING, NullHandler, getLogger
class FtdiLogger:
log = getLogger('pyftdi')
log.addHandler(NullHandler())
log.setLevel(level=WARNING)
@classmethod
def set_formatter(cls, formatter):
handlers = list(cls.log.handlers)
for handler in handlers:
handler.setFormatter(formatter)
@classmethod
def get_level(cls):
return cls.log.getEffectiveLevel()
@classmethod
def set_level(cls, level):
cls.log.setLevel(level=level)
|
define({
"_themeLabel": "Mücevher Kutusu Teması",
"_layout_default": "Varsayılan düzen",
"_layout_layout1": "Düzen 1",
"emptyDocablePanelTip": "Araç eklemek için Araç sekmesinde + düğmesine tıklayın. "
});
|
# Copyright (c) 2019 VMware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
from vio.vsphere import utils
from vio.vsphere import ovf
from pyVmomi import vim
# from pyVmomi.vim.vm.device import VirtualEthernetCard
from pyVim import connect
import paramiko
import os
# import yaml
import requests
def new_vc():
host = os.getenv("VSPHERE_HOST")
username = os.getenv("VSPHERE_USER")
password = os.getenv("VSPHERE_PASS")
nvc = VCenter(host, username, password)
return nvc
def new_esxi():
host = os.getenv("ESXI_HOST")
username = os.getenv("ESXI_USER")
password = os.getenv("ESXI_PASS")
nesxi = Esxi(host, username, password)
return nesxi
class Esxi(object):
def __init__(self, host=None, username=None, password=None):
if not (host and username and password):
raise Exception("host or username or password not specified")
self.host = host
self.username = username
self.password = password
self.ssh = self.get_ssh_session()
def get_ssh_session(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.host, username=self.username, password=self.password)
return ssh
def exec_cmd(self, cmd):
ssh_stdin, ssh_stdout, ssh_stderr = self.ssh.exec_command(cmd)
# import ipdb; ipdb.set_trace()
return {
"stdin": ssh_stdin.read() if ssh_stdin.readable() else "",
"stdout": ssh_stdout.read() if ssh_stdout.readable() else "",
"stderr": ssh_stderr.read() if ssh_stderr.readable() else "",
}
def flat_vmdk(self, datastore, vmdk):
target_vmdk = vmdk.rstrip(".vmdk") + "-new.vmdk"
print("Extending %s to %s" % (vmdk, target_vmdk))
vmdk_path = "/vmfs/volumes/%s/%s" % (datastore, vmdk)
target_path = "/vmfs/volumes/%s/%s" % (datastore, target_vmdk)
cmd = "vmkfstools -i %s %s" % (vmdk_path, target_path)
output = self.exec_cmd(cmd)
if output["stderr"]:
raise Exception(output["stderr"])
output["target_vmdk"] = target_vmdk
return output
class VCenter(object):
def __init__(self, host=None, username=None, password=None):
if not (host and username and password):
raise Exception("host or username or password not specified")
self.host = host
self.username = username
self.password = password
self.datacenter = ""
self.cluster = ""
self.datastore = ""
self.insecure = True
self.service_instance = connect.SmartConnectNoSSL(
host=self.host, user=self.username, pwd=self.password)
self.vcontent = self.service_instance.RetrieveContent()
# self.GetClient()
def clone_vm(self, src, dst, power_on=False, wait=True):
pass
def wait_for_task(self, task):
""" wait for a vCenter task to finish """
task_done = False
while not task_done:
if task.info.state == 'success':
return task.info.result
if task.info.state == 'error':
raise Exception(task.info.error.msg)
# print("there was an error")
# task_done = True
def find_datastore(self, ds_name):
datacenters_object_view = \
self.vcontent.viewManager.CreateContainerView(
self.vcontent.rootFolder,
[vim.Datacenter],
True)
datacenter = None
datastore = None
for dc in datacenters_object_view.view:
datastores_object_view = \
self.vcontent.viewManager.CreateContainerView(
dc,
[vim.Datastore],
True)
for ds in datastores_object_view.view:
if ds.info.name == ds_name:
datacenter = dc
datastore = ds
return datacenter, datastore
return datacenter, datastore
def upload_file(self, filepath, datastore, folder="onap-test"):
if not os.path.exists(filepath):
raise Exception("%s not exists" % filepath)
print("Getting datastore %s" % datastore)
dc, ds = self.find_datastore(datastore)
files = [filepath, filepath.rstrip(".vmdk")+"-flat.vmdk"]
upload_count = 0
for fp in files:
if not os.path.exists(fp):
continue
upload_count += 1
file_name = fp.split("/")[-1]
remote_file = "/" + folder + "/" + file_name
resource = "/folder" + remote_file
params = {"dsName": ds.info.name,
"dcPath": dc.name}
http_url = "https://" + self.host + ":443" + resource
# print(http_url)
# si, vconetnt = self.GetClient()
# get cookies
client_cookie = self.service_instance._stub.cookie
cookie_name = client_cookie.split("=", 1)[0]
cookie_value = client_cookie.split("=", 1)[1].split(";", 1)[0]
cookie_path = client_cookie.split("=", 1)[1].split(
";", 1)[1].split(";", 1)[0].lstrip()
cookie_text = " " + cookie_value + "; $" + cookie_path
# Make a cookie
cookie = dict()
cookie[cookie_name] = cookie_text
# Get the request headers set up
headers = {'Content-Type': 'application/octet-stream'}
with open(fp, "rb") as f:
# Connect and upload the file
print("Uploading file %s" % filepath)
resp = requests.put(http_url,
params=params,
data=f,
# files={"file": f},
headers=headers,
cookies=cookie,
verify=False)
# import ipdb; ipdb.set_trace()
if resp.status_code not in [200, 201]:
raise Exception("failed to upload %s to %s: %s" % (
filepath, datastore, resp.content))
print(resp)
print("upload success")
return upload_count
def deploy_ovf(self, vmdk_path, ovf_path=None, datacenter=None,
cluster=None, datastore=None):
if not datacenter and not self.datacenter:
raise Exception("not set datacenter")
if not cluster and not self.cluster:
raise Exception("not set cluster")
if not datastore and not self.datastore:
raise Exception("not set datastore")
# if not ovf_path:
# raise Exception("not set ovf_path")
ovf.deploy_ovf(self.service_instance, vmdk_path, ovf_path,
datacenter, cluster, datastore)
print("Deploy success.")
def deploy_ova(self, ova_path, datacenter=None, cluster=None,
datastore=None):
pass
def validate_image(self, vmdk_path, vm_name):
# import ipdb; ipdb.set_trace()
print("finding vm %s" % vm_name)
vmdk_name = vmdk_path.split("/")[-1]
vm = self.find_vm(vm_name)
dc = vm.datacenter
cluster = vm.cluster
ds = vm.status()['datastores'][0]
# vmdk_name = filepath.split("/")[-1]
print("uploading vmdk file %s" % vmdk_name)
ovf.deploy_ovf(self.service_instance, vmdk_path, ovf_path=None,
datacenter=dc.name, cluster=cluster.name,
datastore=ds.name)
tmp_vm = self.find_vm("vmtest-template")
print("attaching disk to vm %s" % vm_name)
# dsfilepath = "[%s] %s/%s" % (
# ds.name, "vmtest-template", "vmdisk1.vmdk")
dsfilepath = tmp_vm.disks()[0].backing.fileName
print("dsfilepath=%s" % dsfilepath)
vm.add_disk(filepath=dsfilepath)
print("power on vm %s" % vm_name)
ret = vm.power_on()
if ret is not None:
raise Exception("error to poweron vm: %s", ret)
print("power off vm %s" % vm_name)
vm.power_off()
print("Cleaning")
vm.remove_disk("Hard disk 2", retain_file=True)
tmp_vm.delete()
def find_ds(self, ds_name):
ds = utils.get_obj(self.vcontent, [vim.Datastore], ds_name)
return ds
def find_dc(self, dc_name):
dc = utils.get_obj(self.vcontent, [vim.Datacenter], dc_name)
return dc
# def find_cluster(self, cluster):
# cluster = utils.get_obj(self.vcontent, [vim.C], name)
def find_vm(self, vm_name):
return VM(self, vm_name)
class VM(object):
def __init__(self, vc, name):
self.vc = vc
vm = utils.get_obj(self.vc.vcontent, [vim.VirtualMachine], name)
if vm is None:
raise Exception("VM %s not found" % name)
self.vm = vm
self.name = name
@property
def datacenter(self):
res = self.vm.resourcePool
while True:
if res is None:
break
if str(res).startswith("'vim.Datacenter"):
return res
res = res.parent
return None
@property
def cluster(self):
res = self.vm.resourcePool
while True:
if res is None:
break
if str(res).startswith("'vim.ClusterComputeResource"):
return res
res = res.parent
return None
def status(self):
ret = {
"name": self.vm.name,
"resource_pool": self.vm.resourcePool,
"cluster": self.cluster,
"datacenter": self.datacenter,
"datastores": [ds for ds in self.vm.datastore],
"power_state": self.vm.runtime.powerState,
}
if self.vm.network:
ret["networks"] = [net for net in self.vm.network]
if self.vm.snapshot:
ret["snapshots"] = [ss for ss in self.vm.snapshot]
return ret
@property
def power_state(self):
return self.vm.runtime.powerState
def power_on(self):
if self.power_state != "poweredOn":
# task = self.vm.PowerOn()
# print("power_on task:", task)
# result = wait_for_task(task)
# print("power_on result:", result)
result = self.vc.wait_for_task(self.vm.PowerOn())
return result
def power_off(self):
if self.power_state != "poweredOff":
# task = self.vm.PowerOff()
# print("power_off task:", task)
# result = wait_for_task(task)
# print("power_off result:", result)
result = self.vc.wait_for_task(self.vm.PowerOff())
return result
def delete(self):
self.power_off()
result = self.vc.wait_for_task(self.vm.Destroy())
return result
def clone(self, dst, wait=True):
print("clone %s to %s" % (self.name, dst))
relospec = vim.vm.RelocateSpec(pool=self.vm.resourcePool)
clonespec = vim.vm.CloneSpec(location=relospec)
clonespec.powerOn = False
task = self.vm.Clone(name=dst, folder=self.vm.parent, spec=clonespec)
print("clone task:", task)
if wait:
print("wait for task:", task)
result = self.vc.wait_for_task(task)
print("task result:", result)
return VM(self.vc, result.name)
return task
def add_nic(self, network_name, nic_type="vmxnet3", mac=None):
spec = vim.vm.ConfigSpec()
nic_spec = vim.vm.device.VirtualDeviceSpec()
nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
if nic_type == "e1000":
nic_spec.device = vim.vm.device.VirtualE1000()
elif nic_type == "e1000e":
nic_spec.device = vim.vm.device.VirtualE1000e()
elif nic_type == 'vmxnet':
nic_spec.device = vim.vm.device.VirtualVmxnet()
elif nic_type == 'vmxnet2':
nic_spec.device = vim.vm.device.VirtualVmxnet2()
elif nic_type == "vmxnet3":
nic_spec.device = vim.vm.device.VirtualVmxnet3()
else:
raise Exception("not supported nic type %s" % nic_type)
network = utils.get_obj(self.vc.vcontent, [vim.Network], network_name)
VirtualEthernetCard = vim.vm.device.VirtualEthernetCard
if isinstance(network, vim.OpaqueNetwork):
nic_spec.device.backing = \
VirtualEthernetCard.OpaqueNetworkBackingInfo()
nic_spec.device.backing.opaqueNetworkType = \
network.summary.opaqueNetworkType
nic_spec.device.backing.opaqueNetworkId = \
network.summary.opaqueNetworkId
elif isinstance(network, vim.dvs.DistributedVirtualPortgroup):
nic_spec.device.backing = \
VirtualEthernetCard.DistributedVirtualPortBackingInfo()
# nic_spec.device.backing.port = network
nic_spec.device.backing.port = vim.dvs.PortConnection()
# nic_spec.device.backing.port.portgroupKey = port.portgroupKey
nic_spec.device.backing.port.portgroupKey = network.key
nic_spec.device.backing.port.switchUuid = \
network.config.distributedVirtualSwitch.uuid
# nic_spec.device.backing.port.switchUuid = port.dvsUuid
# nic_spec.device.backing.port.portKey = port.key
else:
nic_spec.device.backing = \
VirtualEthernetCard.NetworkBackingInfo()
nic_spec.device.backing.useAutoDetect = False
# nic_spec.device.backing.network = network
nic_spec.device.backing.deviceName = network
nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nic_spec.device.connectable.startConnected = True
nic_spec.device.connectable.allowGuestControl = True
nic_spec.device.connectable.connected = False
nic_spec.device.connectable.status = 'untried'
nic_spec.device.wakeOnLanEnabled = True
nic_spec.device.addressType = 'assigned'
if mac:
nic_spec.device.macAddress = mac
spec.deviceChange = [nic_spec]
task = self.vm.ReconfigVM_Task(spec=spec)
result = self.vc.wait_for_task(task)
# result == None
return result
def remove_nics(self):
nics = []
for dev in self.vm.config.hardware.device:
if isinstance(dev, vim.vm.device.VirtualEthernetCard):
nics.append(dev)
spec = vim.vm.ConfigSpec()
spec.deviceChange = []
for dev in nics:
virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
virtual_nic_spec.operation = \
vim.vm.device.VirtualDeviceSpec.Operation.remove
virtual_nic_spec.device = dev
spec.deviceChange.append(virtual_nic_spec)
task = self.vm.ReconfigVM_Task(spec=spec)
result = self.vc.wait_for_task(task)
# result == None
return result
def add_disk(self, disk_size=0, disk_type="thin", filepath=None,
wait=True):
spec = vim.vm.ConfigSpec()
unit_number = 0
for dev in self.vm.config.hardware.device:
if hasattr(dev.backing, 'fileName'):
unit_number = int(dev.unitNumber) + 1
# unit_number 7 reserved for scsi controller
if unit_number == 7:
unit_number += 1
if isinstance(dev, vim.vm.device.VirtualSCSIController):
controller = dev
dev_changes = []
if disk_size <= 0 and not filepath:
raise Exception("Neither disk_size nor filepath specified")
disk_spec = vim.vm.device.VirtualDeviceSpec()
if not filepath:
disk_spec.fileOperation = "create"
disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
disk_spec.device = vim.vm.device.VirtualDisk()
disk_spec.device.backing = \
vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
if disk_type == 'thin':
disk_spec.device.backing.thinProvisioned = True
if filepath:
disk_spec.device.backing.fileName = filepath
disk_spec.device.backing.diskMode = 'persistent'
disk_spec.device.unitNumber = unit_number
if not filepath:
new_disk_kb = int(disk_size) * 1024 * 1024
disk_spec.device.capacityInKB = new_disk_kb
disk_spec.device.controllerKey = controller.key
dev_changes.append(disk_spec)
spec.deviceChange = dev_changes
task = self.vm.ReconfigVM_Task(spec=spec)
if disk_size:
print("Adding a %sGB disk to vm %s" % (disk_size, self.name))
else:
print("Attaching %s disk to vm %s" % (filepath, self.name))
if wait:
ret = self.vc.wait_for_task(task)
return ret
return task
def remove_disk(self, disk_label, retain_file=False, wait=True):
print("Attempt to remove %s from %s" % (disk_label, self.name))
virtual_hdd_device = None
if isinstance(disk_label, int):
if disk_label < 1:
return {"error": (
"invalid disk index %d, disk "
"index starting from 1" % disk_label)
}
count = 0
for dev in self.vm.config.hardware.device:
if isinstance(dev, vim.vm.device.VirtualDisk):
count += 1
if count == disk_label:
virtual_hdd_device = dev
elif isinstance(disk_label, str):
for dev in self.vm.config.hardware.device:
if (isinstance(dev, vim.vm.device.VirtualDisk) and
dev.deviceInfo.label == disk_label):
virtual_hdd_device = dev
if virtual_hdd_device is None:
return {"error": "disk %s not found" % disk_label}
virtual_hdd_spec = vim.vm.device.VirtualDeviceSpec()
virtual_hdd_spec.operation = \
vim.vm.device.VirtualDeviceSpec.Operation.remove
if not retain_file:
virtual_hdd_spec.fileOperation = \
vim.vm.device.VirtualDeviceSpec.FileOperation.destroy
virtual_hdd_spec.device = virtual_hdd_device
spec = vim.vm.ConfigSpec()
spec.deviceChange = [virtual_hdd_spec]
task = self.vm.ReconfigVM_Task(spec=spec)
if wait:
ret = self.vc.wait_for_task(task)
return ret
return task
def disks(self):
disks = []
for dev in self.vm.config.hardware.device:
if isinstance(dev, vim.vm.device.VirtualDisk):
disks.append(dev)
return disks
|
/**
* @file 平移变换
* @author mengke01(kekee000@gmail.com)
*/
define(
function (require) {
var lang = require('common/lang');
var pathAdjust = require('graphics/pathAdjust');
/**
* 移动对象
*
* @param {Object} camera 镜头对象
* @param {boolean} fixX 固定X
* @param {boolean} fixY 固定Y
* @param {boolean} enableSorption 是否吸附
*/
function moveTransform(camera, fixX, fixY, enableSorption) {
var x = fixX ? 0 : (camera.x - camera.startX);
var y = fixY ? 0 : (camera.y - camera.startY);
// 更新shape
var shapes = this.shapes;
var bound = this.bound;
var coverLayer = this.editor.coverLayer;
var boundShape = coverLayer.getShape('bound');
// 吸附选项
if (enableSorption) {
var centerX = bound.x + bound.width / 2;
var centerY = bound.y + bound.height / 2;
var sorptionColor = this.editor.options.sorption.sorptionColor;
var sorptionLineWidth = this.editor.options.sorption.sorptionLineWidth;
var sorptionFont = this.editor.options.sorption.sorptionFont;
var i;
var result;
if (!fixX) {
// 设置吸附辅助线
var sorptionShapeX = coverLayer.getShape('sorptionX');
if (!sorptionShapeX) {
sorptionShapeX = coverLayer.addShape({
type: 'line',
id: 'sorptionX',
style: {
strokeColor: sorptionColor,
lineWidth : sorptionLineWidth,
font : sorptionFont
},
p0: {},
p1: {},
offset : { x : x , y : y }
});
}
var posXList = [this.bound.x, centerX, this.bound.x + this.bound.width];
for (i = 0; i < 3; i++) {
result = this.editor.sorption.detectX(posXList[i] + x);
if (result) {
x = result.axis - posXList[i];
sorptionShapeX.p0.x = sorptionShapeX.p1.x = result.axis;
sorptionShapeX.p0.y = centerY + y;
sorptionShapeX.p1.y = result.y;
sorptionShapeX.disabled = false;
sorptionShapeX.distY = Math.abs(sorptionShapeX.p0.y - sorptionShapeX.p1.y) * (1/camera.scale);
break;
}
}
if (i === 3) {
sorptionShapeX.disabled = true;
}
}
if (!fixY) {
// 设置吸附辅助线
var sorptionShapeY = coverLayer.getShape('sorptionY');
if (!sorptionShapeY) {
sorptionShapeY = coverLayer.addShape({
type: 'line',
id: 'sorptionY',
style: {
strokeColor: sorptionColor,
lineWidth : sorptionLineWidth,
font : sorptionFont
},
p0: {},
p1: {},
offset : { x : x , y : y }
});
}
var posYList = [this.bound.y, centerY, this.bound.y + this.bound.height];
for (i = 0; i < 3; i++) {
result = this.editor.sorption.detectY(posYList[i] + y);
if (result) {
y = result.axis - posYList[i];
sorptionShapeY.p0.x = centerX + x;
sorptionShapeY.p1.x = result.x;
sorptionShapeY.p0.y = sorptionShapeY.p1.y = result.axis;
sorptionShapeY.distX = Math.abs(sorptionShapeY.p0.x - sorptionShapeY.p1.x) * (1/camera.scale);
sorptionShapeY.disabled = false;
break;
}
}
if (i === 3) {
sorptionShapeY.disabled = true;
}
}
}
this.coverShapes.forEach(function (coverShape, index) {
var shape = lang.clone(shapes[index]);
pathAdjust(shape.points, 1, 1, x, y);
lang.extend(coverShape, shape);
});
// 更新边界
boundShape.points = pathAdjust(
[
{x: bound.x, y: bound.y},
{x: bound.x + bound.width, y: bound.y},
{x: bound.x + bound.width, y: bound.y + bound.height},
{x: bound.x, y: bound.y + bound.height}
],
1, 1, x, y
);
coverLayer.refresh();
}
return moveTransform;
}
);
|
import React from "react";
import * as api from "../../api";
class NewTweet extends React.Component {
state = {
text: ""
};
handleInputChange = event => {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
};
handleFormSubmit = async event => {
event.preventDefault();
const { text } = this.state;
if (text) {
const payload = { text };
try {
await api.postTweet(payload);
this.props.history.push("/");
} catch (error) {
console.log(error);
}
}
};
render() {
const { text } = this.state;
return (
<form onSubmit={this.handleFormSubmit}>
<h3>New Tweet Form</h3>
<div>
<div>
<label>Text</label>
<span> * </span>
</div>
<textarea
name="text"
type="text"
value={text}
onChange={this.handleInputChange}
required
rows="8"
style={styles.textarea}
maxLength={140}
/>
</div>
<input type="submit" value="Submit!" />
</form>
);
}
}
const styles = {
textarea: {
width: "100%"
}
};
export default NewTweet;
|
import fileinput
lines = list(l for l in fileinput.input())
def mark(grid, n):
s = 0
for i in range(5):
for j in range(5):
if grid[i][j] == n:
grid[i][j] = -1
if grid[i][j] != -1:
s += grid[i][j]
for i in range(5):
if grid[i].count(-1) == 5:
return s
if sum(int(grid[j][i] == -1) for j in range(5)) == 5:
return s
def main():
nums = list(map(int, lines[0].split(',')))
grids = []
for i in range(2, len(lines), 6):
grid = []
for j in range(i, i + 5):
grid.append(list(map(int, lines[j].strip().split())))
grids.append(grid)
assert len(grids) == 100
for n in nums:
for g in grids:
assert len(g) == 5
for col in g:
assert len(col) == 5
score = mark(g, n)
if score:
print(g)
print(n, score)
print(n * score)
exit(0)
main()
|
"use strict";
exports.__esModule = true;
/**
* Checks if value is inside the range.
*/
function inRange(val, min, max, threshold) {
if (threshold === void 0) { threshold = 0; }
return val + threshold >= min && val - threshold <= max;
}
exports["default"] = inRange;
|
from ..core import Solution
from ..core import Experiment
import numpy as np
class DynamicSolver(Experiment):
def __init__(self, instance, solution=None):
self.log = ""
if solution is None:
solution = Solution({"include": []})
super().__init__(instance, solution)
self.log += "Initialized\n"
def solve(self, config):
self.log += "Converting data lists to arrays\n"
self.weights = np.array(self.instance.data["weights"])
self.values = np.array(self.instance.data["values"])
self.log += "Solver chosen : Dynamic\n"
idx = self.weights.argsort()
self.weights = self.weights[idx]
self.values = self.values[idx]
self.log += "Launching dynamic solver \n"
res = self.dyn_solver()
self.log += "Sorting the final arrays\n"
idx2 = idx.argsort()
res["include"] = (np.array(res["include"])[idx2]).tolist()
self.solver = "Dynamic"
for i in range(len(res["include"])):
if res["include"][i] == 1:
self.solution.data["include"].append({"id": i})
return 1
def dyn_solver(self): #
U = np.zeros(
(
self.instance.data["nb_objects"],
self.instance.data["weight_capacity"] + 1 - self.weights[0],
2,
)
) # self.instance.data["weight_capacity"]
self.log += "Initializing the table\n"
## U[i, j, 0] : solution of the problem for the i first items and a backpack of capacity j
## U[i, j, 1] : 0 if the item number i is not taken, 1 if it is.
for j in range(0, self.instance.data["weight_capacity"] + 1 - self.weights[0]):
U[0, j, 0] = self.values[0]
U[0, j, 1] = 1
self.log += "Filling table U\n"
## Filling the table U. For each (i, j), U(i, j) = V(i, j + w0).
for i in range(1, self.instance.data["nb_objects"]):
for j in range(
0, self.instance.data["weight_capacity"] + 1 - self.weights[0]
):
if j + self.weights[0] < self.weights[i]:
U[i, j, 0] = U[i - 1, j, 0]
U[i, j, 1] = 0
elif (j + self.weights[0] == self.weights[i]) or (
j + self.weights[0] - self.weights[i] < self.weights[0]
):
U[i, j, 0] = max(U[i - 1, j, 0], self.values[i])
if U[i - 1, j, 0] >= self.values[i]:
U[i, j, 1] = 0
else:
U[i, j, 1] = 1
else:
U[i, j, 0] = max(
U[i - 1, j, 0],
U[i - 1, j - self.weights[i], 0] + self.values[i],
)
if (
U[i - 1, j, 0]
>= U[i - 1, j - self.weights[i], 0] + self.values[i]
):
U[i, j, 1] = 0
else:
U[i, j, 1] = 1
res_dict = dict()
res_dict["include"] = [0] * self.instance.data["nb_objects"]
self.log += "Tracing back\n"
## Tracing back from the end of the tab to the top to get all the included items
index_v = self.instance.data["weight_capacity"] - self.weights[0]
for i in range(self.instance.data["nb_objects"] - 1, -1, -1):
if U[i, index_v, 1] == 1 and index_v >= 0:
index_v = index_v - self.weights[i]
res_dict["include"][i] = 1
# res_dict["weight"] += self.weights[i]
# res_dict["value"] += self.values[i]
self.log += "Solving complete\n"
return res_dict
|
/**
* @description MeshCentral web server
* @author Ylian Saint-Hilaire
* @copyright Intel Corporation 2018-2020
* @license Apache-2.0
* @version v0.0.1
*/
/*jslint node: true */
/*jshint node: true */
/*jshint strict:false */
/*jshint -W097 */
/*jshint esversion: 6 */
'use strict';
/*
class SerialTunnel extends require('stream').Duplex {
constructor(options) { super(options); this.forwardwrite = null; }
updateBuffer(chunk) { this.push(chunk); }
_write(chunk, encoding, callback) { if (this.forwardwrite != null) { this.forwardwrite(chunk); } else { console.err("Failed to fwd _write."); } if (callback) callback(); } // Pass data written to forward
_read(size) { } // Push nothing, anything to read should be pushed from updateBuffer()
}
*/
// Older NodeJS does not support the keyword "class", so we do without using this syntax
// TODO: Validate that it's the same as above and that it works.
function SerialTunnel(options) {
var obj = new require('stream').Duplex(options);
obj.forwardwrite = null;
obj.updateBuffer = function (chunk) { this.push(chunk); };
obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } else { console.err("Failed to fwd _write."); } if (callback) callback(); }; // Pass data written to forward
obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
return obj;
}
// ExpressJS login sample
// https://github.com/expressjs/express/blob/master/examples/auth/index.js
// Polyfill startsWith/endsWith for older NodeJS
if (!String.prototype.startsWith) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; }
if (!String.prototype.endsWith) { String.prototype.endsWith = function (searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.lastIndexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; }
// Construct a HTTP server object
module.exports.CreateWebServer = function (parent, db, args, certificates) {
var obj = {}, i = 0;
// Modules
obj.fs = require('fs');
obj.net = require('net');
obj.tls = require('tls');
obj.path = require('path');
obj.bodyParser = require('body-parser');
obj.session = require('cookie-session');
obj.exphbs = require('express-handlebars');
obj.crypto = require('crypto');
obj.common = require('./common.js');
obj.express = require('express');
obj.meshAgentHandler = require('./meshagent.js');
obj.meshRelayHandler = require('./meshrelay.js');
obj.meshDeviceFileHandler = require('./meshdevicefile.js');
obj.meshDesktopMultiplexHandler = require('./meshdesktopmultiplex.js');
obj.meshIderHandler = require('./amt/amt-ider.js');
obj.meshUserHandler = require('./meshuser.js');
obj.interceptor = require('./interceptor');
const constants = (obj.crypto.constants ? obj.crypto.constants : require('constants')); // require('constants') is deprecated in Node 11.10, use require('crypto').constants instead.
// Setup WebAuthn / FIDO2
obj.webauthn = require('./webauthn.js').CreateWebAuthnModule();
// Variables
obj.args = args;
obj.parent = parent;
obj.filespath = parent.filespath;
obj.db = db;
obj.app = obj.express();
if (obj.args.agentport) { obj.agentapp = obj.express(); }
if (args.compression !== false) { obj.app.use(require('compression')()); }
obj.app.disable('x-powered-by');
obj.tlsServer = null;
obj.tcpServer = null;
obj.certificates = certificates;
obj.users = {}; // UserID --> User
obj.meshes = {}; // MeshID --> Mesh (also called device group)
obj.userGroups = {}; // UGrpID --> User Group
obj.userAllowedIp = args.userallowedip; // List of allowed IP addresses for users
obj.agentAllowedIp = args.agentallowedip; // List of allowed IP addresses for agents
obj.agentBlockedIp = args.agentblockedip; // List of blocked IP addresses for agents
obj.tlsSniCredentials = null;
obj.dnsDomains = {};
obj.relaySessionCount = 0;
obj.relaySessionErrorCount = 0;
obj.blockedUsers = 0;
obj.blockedAgents = 0;
obj.renderPages = null;
obj.renderLanguages = [];
// Mesh Rights
const MESHRIGHT_EDITMESH = 1;
const MESHRIGHT_MANAGEUSERS = 2;
const MESHRIGHT_MANAGECOMPUTERS = 4;
const MESHRIGHT_REMOTECONTROL = 8;
const MESHRIGHT_AGENTCONSOLE = 16;
const MESHRIGHT_SERVERFILES = 32;
const MESHRIGHT_WAKEDEVICE = 64;
const MESHRIGHT_SETNOTES = 128;
// Site rights
const SITERIGHT_SERVERBACKUP = 1;
const SITERIGHT_MANAGEUSERS = 2;
const SITERIGHT_SERVERRESTORE = 4;
const SITERIGHT_FILEACCESS = 8;
const SITERIGHT_SERVERUPDATE = 16;
const SITERIGHT_LOCKED = 32;
// Setup SSPI authentication if needed
if ((obj.parent.platform == 'win32') && (obj.args.nousers != true) && (obj.parent.config != null) && (obj.parent.config.domains != null)) {
for (i in obj.parent.config.domains) { if (obj.parent.config.domains[i].auth == 'sspi') { var nodeSSPI = require('node-sspi'); obj.parent.config.domains[i].sspi = new nodeSSPI({ retrieveGroups: true, offerBasic: false }); } }
}
// Perform hash on web certificate and agent certificate
obj.webCertificateHash = obj.defaultWebCertificateHash = parent.certificateOperations.getPublicKeyHashBinary(obj.certificates.web.cert);
obj.webCertificateHashs = { '': obj.webCertificateHash };
obj.webCertificateHashBase64 = Buffer.from(obj.webCertificateHash, 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
obj.webCertificateFullHash = obj.defaultWebCertificateFullHash = parent.certificateOperations.getCertHashBinary(obj.certificates.web.cert);
obj.webCertificateFullHashs = { '': obj.webCertificateFullHash };
obj.agentCertificateHashHex = parent.certificateOperations.getPublicKeyHash(obj.certificates.agent.cert);
obj.agentCertificateHashBase64 = Buffer.from(obj.agentCertificateHashHex, 'hex').toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
obj.agentCertificateAsn1 = parent.certificateOperations.forge.asn1.toDer(parent.certificateOperations.forge.pki.certificateToAsn1(parent.certificateOperations.forge.pki.certificateFromPem(parent.certificates.agent.cert))).getBytes();
// Compute the hash of all of the web certificates for each domain
for (var i in obj.parent.config.domains) {
if (obj.parent.config.domains[i].certhash != null) {
// If the web certificate hash is provided, use it.
obj.webCertificateHashs[i] = obj.webCertificateFullHashs[i] = Buffer.from(obj.parent.config.domains[i].certhash, 'hex').toString('binary');
if (obj.parent.config.domains[i].certkeyhash != null) { obj.webCertificateHashs[i] = Buffer.from(obj.parent.config.domains[i].certkeyhash, 'hex').toString('binary'); }
} else if ((obj.parent.config.domains[i].dns != null) && (obj.parent.config.domains[i].certs != null)) {
// If the domain has a different DNS name, use a different certificate hash.
// Hash the full certificate
obj.webCertificateFullHashs[i] = parent.certificateOperations.getCertHashBinary(obj.parent.config.domains[i].certs.cert);
try {
// Decode a RSA certificate and hash the public key.
obj.webCertificateHashs[i] = parent.certificateOperations.getPublicKeyHashBinary(obj.parent.config.domains[i].certs.cert);
} catch (ex) {
// This may be a ECDSA certificate, hash the entire cert.
obj.webCertificateHashs[i] = obj.webCertificateFullHashs[i];
}
} else if ((obj.parent.config.domains[i].dns != null) && (obj.certificates.dns[i] != null)) {
// If this domain has a DNS and a matching DNS cert, use it. This case works for wildcard certs.
obj.webCertificateFullHashs[i] = parent.certificateOperations.getCertHashBinary(obj.certificates.dns[i].cert);
obj.webCertificateHashs[i] = parent.certificateOperations.getPublicKeyHashBinary(obj.certificates.dns[i].cert);
} else if (i != '') {
// For any other domain, use the default cert.
obj.webCertificateFullHashs[i] = obj.webCertificateFullHashs[''];
obj.webCertificateHashs[i] = obj.webCertificateHashs[''];
}
}
// If we are running the legacy swarm server, compute the hash for that certificate
if (parent.certificates.swarmserver != null) {
obj.swarmCertificateAsn1 = parent.certificateOperations.forge.asn1.toDer(parent.certificateOperations.forge.pki.certificateToAsn1(parent.certificateOperations.forge.pki.certificateFromPem(parent.certificates.swarmserver.cert))).getBytes();
obj.swarmCertificateHash384 = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.swarmserver.cert).publicKey, { md: parent.certificateOperations.forge.md.sha384.create(), encoding: 'binary' });
obj.swarmCertificateHash256 = parent.certificateOperations.forge.pki.getPublicKeyFingerprint(parent.certificateOperations.forge.pki.certificateFromPem(obj.certificates.swarmserver.cert).publicKey, { md: parent.certificateOperations.forge.md.sha256.create(), encoding: 'binary' });
}
// Main lists
obj.wsagents = {}; // NodeId --> Agent
obj.wsagentsWithBadWebCerts = {}; // NodeId --> Agent
obj.wsagentsDisconnections = {};
obj.wsagentsDisconnectionsTimer = null;
obj.duplicateAgentsLog = {};
obj.wssessions = {}; // UserId --> Array Of Sessions
obj.wssessions2 = {}; // "UserId + SessionRnd" --> Session (Note that the SessionId is the UserId + / + SessionRnd)
obj.wsPeerSessions = {}; // ServerId --> Array Of "UserId + SessionRnd"
obj.wsPeerSessions2 = {}; // "UserId + SessionRnd" --> ServerId
obj.wsPeerSessions3 = {}; // ServerId --> UserId --> [ SessionId ]
obj.sessionsCount = {}; // Merged session counters, used when doing server peering. UserId --> SessionCount
obj.wsrelays = {}; // Id -> Relay
obj.desktoprelays = {}; // Id -> Desktop Multiplexor Relay
obj.wsPeerRelays = {}; // Id -> { ServerId, Time }
var tlsSessionStore = {}; // Store TLS session information for quick resume.
var tlsSessionStoreCount = 0; // Number of cached TLS session information in store.
// Setup randoms
obj.crypto.randomBytes(48, function (err, buf) { obj.httpAuthRandom = buf; });
obj.crypto.randomBytes(16, function (err, buf) { obj.httpAuthRealm = buf.toString('hex'); });
obj.crypto.randomBytes(48, function (err, buf) { obj.relayRandom = buf; });
// Get non-english web pages and emails
getRenderList();
getEmailLanguageList();
// Setup DNS domain TLS SNI credentials
{
var dnscount = 0;
obj.tlsSniCredentials = {};
for (i in obj.certificates.dns) { if (obj.parent.config.domains[i].dns != null) { obj.dnsDomains[obj.parent.config.domains[i].dns.toLowerCase()] = obj.parent.config.domains[i]; obj.tlsSniCredentials[obj.parent.config.domains[i].dns] = obj.tls.createSecureContext(obj.certificates.dns[i]).context; dnscount++; } }
if (dnscount > 0) { obj.tlsSniCredentials[''] = obj.tls.createSecureContext({ cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.web.ca }).context; } else { obj.tlsSniCredentials = null; }
}
function TlsSniCallback(name, cb) {
var c = obj.tlsSniCredentials[name];
if (c != null) {
cb(null, c);
} else {
cb(null, obj.tlsSniCredentials['']);
}
}
function EscapeHtml(x) { if (typeof x == 'string') return x.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/"/g, '"').replace(/'/g, '''); if (typeof x == 'boolean') return x; if (typeof x == 'number') return x; }
//function EscapeHtmlBreaks(x) { if (typeof x == "string") return x.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/"/g, '"').replace(/'/g, ''').replace(/\r/g, '<br />').replace(/\n/g, '').replace(/\t/g, ' '); if (typeof x == "boolean") return x; if (typeof x == "number") return x; }
// Fetch all users from the database, keep this in memory
obj.db.GetAllType('user', function (err, docs) {
obj.common.unEscapeAllLinksFieldName(docs);
var domainUserCount = {}, i = 0;
for (i in parent.config.domains) { domainUserCount[i] = 0; }
for (i in docs) { var u = obj.users[docs[i]._id] = docs[i]; domainUserCount[u.domain]++; }
for (i in parent.config.domains) {
if (domainUserCount[i] == 0) {
// If newaccounts is set to no new accounts, but no accounts exists, temporarly allow account creation.
//if ((parent.config.domains[i].newaccounts === 0) || (parent.config.domains[i].newaccounts === false)) { parent.config.domains[i].newaccounts = 2; }
console.log('Server ' + ((i == '') ? '' : (i + ' ')) + 'has no users, next new account will be site administrator.');
}
}
// Fetch all device groups (meshes) from the database, keep this in memory
// As we load things in memory, we will also be doing some cleaning up.
// We will not save any clean up in the database right now, instead it will be saved next time there is a change.
obj.db.GetAllType('mesh', function (err, docs) {
obj.common.unEscapeAllLinksFieldName(docs);
for (var i in docs) { obj.meshes[docs[i]._id] = docs[i]; } // Get all meshes, including deleted ones.
// Fetch all user groups from the database, keep this in memory
obj.db.GetAllType('ugrp', function (err, docs) {
obj.common.unEscapeAllLinksFieldName(docs);
// Perform user group link cleanup
for (var i in docs) {
const ugrp = docs[i];
if (ugrp.links != null) {
for (var j in ugrp.links) {
if (j.startsWith('user/') && (obj.users[j] == null)) { delete ugrp.links[j]; } // User group has a link to a user that does not exist
else if (j.startsWith('mesh/') && ((obj.meshes[j] == null) || (obj.meshes[j].deleted != null))) { delete ugrp.links[j]; } // User has a link to a device group that does not exist
}
}
obj.userGroups[docs[i]._id] = docs[i]; // Get all user groups
}
// Perform device group link cleanup
for (var i in obj.meshes) {
const mesh = obj.meshes[i];
if (mesh.links != null) {
for (var j in mesh.links) {
if (j.startsWith('ugrp/') && (obj.userGroups[j] == null)) { delete mesh.links[j]; } // Device group has a link to a user group that does not exist
else if (j.startsWith('user/') && (obj.users[j] == null)) { delete mesh.links[j]; } // Device group has a link to a user that does not exist
}
}
}
// Perform user link cleanup
for (var i in obj.users) {
const user = obj.users[i];
if (user.links != null) {
for (var j in user.links) {
if (j.startsWith('ugrp/') && (obj.userGroups[j] == null)) { delete user.links[j]; } // User has a link to a user group that does not exist
else if (j.startsWith('mesh/') && ((obj.meshes[j] == null) || (obj.meshes[j].deleted != null))) { delete user.links[j]; } // User has a link to a device group that does not exist
//else if (j.startsWith('node/') && (obj.nodes[j] == null)) { delete user.links[j]; } // TODO
}
//if (Object.keys(user.links).length == 0) { delete user.links; }
}
}
// We loaded the users, device groups and user group state, start the server
serverStart();
});
});
});
// Clean up a device, used before saving it in the database
obj.cleanDevice = function (device) {
// Check device links, if a link points to an unknown user, remove it.
if (device.links != null) {
for (var j in device.links) {
if ((obj.users[j] == null) && (obj.userGroups[j] == null)) {
delete device.links[j];
if (Object.keys(device.links).length == 0) { delete device.links; }
}
}
}
return device;
}
// Return statistics about this web server
obj.getStats = function () {
return {
users: Object.keys(obj.users).length,
meshes: Object.keys(obj.meshes).length,
dnsDomains: Object.keys(obj.dnsDomains).length,
relaySessionCount: obj.relaySessionCount,
relaySessionErrorCount: obj.relaySessionErrorCount,
wsagents: Object.keys(obj.wsagents).length,
wsagentsDisconnections: Object.keys(obj.wsagentsDisconnections).length,
wsagentsDisconnectionsTimer: Object.keys(obj.wsagentsDisconnectionsTimer).length,
wssessions: Object.keys(obj.wssessions).length,
wssessions2: Object.keys(obj.wssessions2).length,
wsPeerSessions: Object.keys(obj.wsPeerSessions).length,
wsPeerSessions2: Object.keys(obj.wsPeerSessions2).length,
wsPeerSessions3: Object.keys(obj.wsPeerSessions3).length,
sessionsCount: Object.keys(obj.sessionsCount).length,
wsrelays: Object.keys(obj.wsrelays).length,
wsPeerRelays: Object.keys(obj.wsPeerRelays).length,
tlsSessionStore: Object.keys(tlsSessionStore).length,
blockedUsers: obj.blockedUsers,
blockedAgents: obj.blockedAgents
};
}
// Agent counters
obj.agentStats = {
createMeshAgentCount: 0,
agentClose: 0,
agentBinaryUpdate: 0,
coreIsStableCount: 0,
verifiedAgentConnectionCount: 0,
clearingCoreCount: 0,
updatingCoreCount: 0,
recoveryCoreIsStableCount: 0,
meshDoesNotExistCount: 0,
invalidPkcsSignatureCount: 0,
invalidRsaSignatureCount: 0,
invalidJsonCount: 0,
unknownAgentActionCount: 0,
agentBadWebCertHashCount: 0,
agentBadSignature1Count: 0,
agentBadSignature2Count: 0,
agentMaxSessionHoldCount: 0,
invalidDomainMeshCount: 0,
invalidMeshTypeCount: 0,
invalidDomainMesh2Count: 0,
invalidMeshType2Count: 0,
duplicateAgentCount: 0,
maxDomainDevicesReached: 0
}
obj.getAgentStats = function () { return obj.agentStats; }
// Authenticate the user
obj.authenticate = function (name, pass, domain, fn) {
if ((typeof (name) != 'string') || (typeof (pass) != 'string') || (typeof (domain) != 'object')) { fn(new Error('invalid fields')); return; }
if (domain.auth == 'ldap') {
if (domain.ldapoptions.url == 'test') {
// Fake LDAP login
var xxuser = domain.ldapoptions[name.toLowerCase()];
if (xxuser == null) {
fn(new Error('invalid password'));
return;
} else {
var username = xxuser['displayName'];
if (domain.ldapusername) { username = xxuser[domain.ldapusername]; }
var shortname = null;
if (domain.ldapuserbinarykey) {
// Use a binary key as the userid
if (xxuser[domain.ldapuserbinarykey]) { shortname = Buffer.from(xxuser[domain.ldapuserbinarykey], 'binary').toString('hex'); }
} else if (domain.ldapuserkey) {
// Use a string key as the userid
if (xxuser[domain.ldapuserkey]) { shortname = xxuser[domain.ldapuserkey]; }
} else {
// Use the default key as the userid
if (xxuser.objectSid) { shortname = Buffer.from(xxuser.objectSid, 'binary').toString('hex').toLowerCase(); }
else if (xxuser.objectGUID) { shortname = Buffer.from(xxuser.objectGUID, 'binary').toString('hex').toLowerCase(); }
else if (xxuser.name) { shortname = xxuser.name; }
else if (xxuser.cn) { shortname = xxuser.cn; }
}
if (username == null) { fn(new Error('no user name')); return; }
if (shortname == null) { fn(new Error('no user identifier')); return; }
var userid = 'user/' + domain.id + '/' + shortname;
var user = obj.users[userid];
var email = null;
if (domain.ldapuseremail) {
email = xxuser[domain.ldapuseremail];
} else if (xxuser.mail) { // use default
email = xxuser.mail;
}
if ('[object Array]' == Object.prototype.toString.call(email)) {
// mail may be multivalued in ldap in which case, answer is an array. Use the 1st value.
email = email[0];
}
if (email) { email = email.toLowerCase(); } // it seems some code otherwhere also lowercase the emailaddress. be compatible.
if (user == null) {
// Create a new user
var user = { type: 'user', _id: userid, name: username, creation: Math.floor(Date.now() / 1000), login: Math.floor(Date.now() / 1000), domain: domain.id };
if (email) { user['email'] = email; user['emailVerified'] = true; }
if (domain.newaccountsrights) { user.siteadmin = domain.newaccountsrights; }
if (obj.common.validateStrArray(domain.newaccountrealms)) { user.groups = domain.newaccountrealms; }
var usercount = 0;
for (var i in obj.users) { if (obj.users[i].domain == domain.id) { usercount++; } }
if (usercount == 0) { user.siteadmin = 4294967295; /*if (domain.newaccounts === 2) { delete domain.newaccounts; }*/ } // If this is the first user, give the account site admin.
// Auto-join any user groups
if (typeof domain.newaccountsusergroups == 'object') {
for (var i in domain.newaccountsusergroups) {
var ugrpid = domain.newaccountsusergroups[i];
if (ugrpid.indexOf('/') < 0) { ugrpid = 'ugrp/' + domain.id + '/' + ugrpid; }
var ugroup = obj.userGroups[ugrpid];
if (ugroup != null) {
// Add group to the user
if (user.links == null) { user.links = {}; }
user.links[ugroup._id] = { rights: 1 };
// Add user to the group
ugroup.links[user._id] = { userid: user._id, name: user.name, rights: 1 };
db.Set(ugroup);
// Notify user group change
var event = { etype: 'ugrp', ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msg: 'Added user ' + user.name + ' to user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user._id], obj, event);
}
}
}
obj.users[user._id] = user;
obj.db.SetUser(user);
var event = { etype: 'user', userid: userid, username: username, account: obj.CloneSafeUser(user), action: 'accountcreate', msg: 'Account created, name is ' + name, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users'], obj, event);
return fn(null, user._id);
} else {
// This is an existing user
// If the display username has changes, update it.
if (user.name != username) {
user.name = username;
obj.db.SetUser(user);
var event = { etype: 'user', userid: userid, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: 'Changed account display name to ' + username, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
}
// Check if user email has changed
var emailreason = null;
if (user.email && !email) { // email unset in ldap => unset
delete user.email;
delete user.emailVerified;
emailreason = 'Unset email (no more email in LDAP)'
} else if (user.email != email) { // update email
user['email'] = email;
user['emailVerified'] = true;
emailreason = 'Set account email to ' + email + '. Sync with LDAP.';
}
if (emailreason) {
obj.db.SetUser(user);
var event = { etype: 'user', userid: userid, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: emailreason, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
}
// If user is locker out, block here.
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
}
} else {
// LDAP login
var LdapAuth = require('ldapauth-fork');
var ldap = new LdapAuth(domain.ldapoptions);
ldap.authenticate(name, pass, function (err, xxuser) {
try { ldap.close(); } catch (ex) { console.log(ex); } // Close the LDAP object
if (err) { fn(new Error('invalid password')); return; }
var shortname = null;
var email = null;
if (domain.ldapuseremail) {
email = xxuser[domain.ldapuseremail];
} else if (xxuser.mail) {
email = xxuser.mail;
}
if ('[object Array]' == Object.prototype.toString.call(email)) {
// mail may be multivalued in ldap in which case, answer would be an array. Use the 1st one.
email = email[0];
}
if (email) { email = email.toLowerCase(); } // it seems some code otherwhere also lowercase the emailaddress. be compatible.
var username = xxuser['displayName'];
if (domain.ldapusername) { username = xxuser[domain.ldapusername]; }
if (domain.ldapuserbinarykey) {
// Use a binary key as the userid
if (xxuser[domain.ldapuserbinarykey]) { shortname = Buffer.from(xxuser[domain.ldapuserbinarykey], 'binary').toString('hex').toLowerCase(); }
} else if (domain.ldapuserkey) {
// Use a string key as the userid
if (xxuser[domain.ldapuserkey]) { shortname = xxuser[domain.ldapuserkey]; }
} else {
// Use the default key as the userid
if (xxuser.objectSid) { shortname = Buffer.from(xxuser.objectSid, 'binary').toString('hex').toLowerCase(); }
else if (xxuser.objectGUID) { shortname = Buffer.from(xxuser.objectGUID, 'binary').toString('hex').toLowerCase(); }
else if (xxuser.name) { shortname = xxuser.name; }
else if (xxuser.cn) { shortname = xxuser.cn; }
}
if (username == null) { fn(new Error('no user name')); return; }
if (shortname == null) { fn(new Error('no user identifier')); return; }
var userid = 'user/' + domain.id + '/' + shortname;
var user = obj.users[userid];
if (user == null) {
// This user does not exist, create a new account.
var user = { type: 'user', _id: userid, name: shortname, creation: Math.floor(Date.now() / 1000), login: Math.floor(Date.now() / 1000), domain: domain.id };
if (email) {
user['email'] = email;
user['emailVerified'] = true;
}
if (domain.newaccountsrights) { user.siteadmin = domain.newaccountsrights; }
if (obj.common.validateStrArray(domain.newaccountrealms)) { user.groups = domain.newaccountrealms; }
var usercount = 0;
for (var i in obj.users) { if (obj.users[i].domain == domain.id) { usercount++; } }
if (usercount == 0) { user.siteadmin = 4294967295; /*if (domain.newaccounts === 2) { delete domain.newaccounts; }*/ } // If this is the first user, give the account site admin.
// Auto-join any user groups
if (typeof domain.newaccountsusergroups == 'object') {
for (var i in domain.newaccountsusergroups) {
var ugrpid = domain.newaccountsusergroups[i];
if (ugrpid.indexOf('/') < 0) { ugrpid = 'ugrp/' + domain.id + '/' + ugrpid; }
var ugroup = obj.userGroups[ugrpid];
if (ugroup != null) {
// Add group to the user
if (user.links == null) { user.links = {}; }
user.links[ugroup._id] = { rights: 1 };
// Add user to the group
ugroup.links[user._id] = { userid: user._id, name: user.name, rights: 1 };
db.Set(ugroup);
// Notify user group change
var event = { etype: 'ugrp', ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msg: 'Added user ' + user.name + ' to user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user._id], obj, event);
}
}
}
obj.users[user._id] = user;
obj.db.SetUser(user);
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountcreate', msg: 'Account created, name is ' + name, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users'], obj, event);
return fn(null, user._id);
} else {
// This is an existing user
// If the display username has changes, update it.
if (user.name != username) {
user.name = username;
obj.db.SetUser(user);
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: 'Changed account display name to ' + username, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
}
// Check if user email has changed
var emailreason = null;
if (user.email && !email) { // email unset in ldap => unset
delete user.email;
delete user.emailVerified;
emailreason = 'Unset email (no more email in LDAP)'
} else if (user.email != email) { // update email
user['email'] = email;
user['emailVerified'] = true;
emailreason = 'Set account email to ' + email + '. Sync with LDAP.';
}
if (emailreason) {
obj.db.SetUser(user);
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: emailreason, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
}
// If user is locker out, block here.
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
});
}
} else {
// Regular login
var user = obj.users['user/' + domain.id + '/' + name.toLowerCase()];
// Query the db for the given username
if (!user) { fn(new Error('cannot find user')); return; }
// Apply the same algorithm to the POSTed password, applying the hash against the pass / salt, if there is a match we found the user
if (user.salt == null) {
fn(new Error('invalid password'));
} else {
if (user.passtype != null) {
// IIS default clear or weak password hashing (SHA-1)
require('./pass').iishash(user.passtype, pass, user.salt, function (err, hash) {
if (err) return fn(err);
if (hash == user.hash) {
// Update the password to the stronger format.
require('./pass').hash(pass, function (err, salt, hash, tag) { if (err) throw err; user.salt = salt; user.hash = hash; delete user.passtype; obj.db.SetUser(user); }, 0);
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
fn(new Error('invalid password'), null, user.passhint);
});
} else {
// Default strong password hashing (pbkdf2 SHA384)
require('./pass').hash(pass, user.salt, function (err, hash, tag) {
if (err) return fn(err);
if (hash == user.hash) {
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { fn('locked'); return; }
return fn(null, user._id);
}
fn(new Error('invalid password'), null, user.passhint);
}, 0);
}
}
}
};
/*
obj.restrict = function (req, res, next) {
console.log('restrict', req.url);
var domain = getDomain(req);
if (req.session.userid) {
next();
} else {
req.session.messageid = 111; // Access denied.
res.redirect(domain.url + 'login');
}
};
*/
// Check if the source IP address is in the IP list, return false if not.
function checkIpAddressEx(req, res, ipList, closeIfThis) {
try {
if (req.connection) {
// HTTP(S) request
if (req.clientIp) { for (var i = 0; i < ipList.length; i++) { if (require('ipcheck').match(req.clientIp, ipList[i])) { if (closeIfThis === true) { res.sendStatus(401); } return true; } } }
if (closeIfThis === false) { res.sendStatus(401); }
} else {
// WebSocket request
if (res.clientIp) { for (var i = 0; i < ipList.length; i++) { if (require('ipcheck').match(res.clientIp, ipList[i])) { if (closeIfThis === true) { try { req.close(); } catch (e) { } } return true; } } }
if (closeIfThis === false) { try { req.close(); } catch (e) { } }
}
} catch (e) { console.log(e); } // Should never happen
return false;
}
// Check if the source IP address is allowed, return domain if allowed
// If there is a fail and null is returned, the request or connection is closed already.
function checkUserIpAddress(req, res) {
if ((parent.config.settings.userblockedip != null) && (checkIpAddressEx(req, res, parent.config.settings.userblockedip, true) == true)) { obj.blockedUsers++; return null; }
if ((parent.config.settings.userallowedip != null) && (checkIpAddressEx(req, res, parent.config.settings.userallowedip, false) == false)) { obj.blockedUsers++; return null; }
const domain = (req.url ? getDomain(req) : getDomain(res));
if (domain == null) { parent.debug('web', 'handleRootRequest: invalid domain.'); try { res.sendStatus(404); } catch (ex) { } return; }
if ((domain.userblockedip != null) && (checkIpAddressEx(req, res, domain.userblockedip, true) == true)) { obj.blockedUsers++; return null; }
if ((domain.userallowedip != null) && (checkIpAddressEx(req, res, domain.userallowedip, false) == false)) { obj.blockedUsers++; return null; }
return domain;
}
// Check if the source IP address is allowed, return domain if allowed
// If there is a fail and null is returned, the request or connection is closed already.
function checkAgentIpAddress(req, res) {
if ((parent.config.settings.agentblockedip != null) && (checkIpAddressEx(req, res, parent.config.settings.agentblockedip, null) == true)) { obj.blockedAgents++; return null; }
if ((parent.config.settings.agentallowedip != null) && (checkIpAddressEx(req, res, parent.config.settings.agentallowedip, null) == false)) { obj.blockedAgents++; return null; }
const domain = (req.url ? getDomain(req) : getDomain(res));
if ((domain.agentblockedip != null) && (checkIpAddressEx(req, res, domain.agentblockedip, null) == true)) { obj.blockedAgents++; return null; }
if ((domain.agentallowedip != null) && (checkIpAddressEx(req, res, domain.agentallowedip, null) == false)) { obj.blockedAgents++; return null; }
return domain;
}
// Return the current domain of the request
// Request or connection says open regardless of the response
function getDomain(req) {
if (req.xdomain != null) { return req.xdomain; } // Domain already set for this request, return it.
if (req.headers.host != null) { var d = obj.dnsDomains[req.headers.host.split(':')[0].toLowerCase()]; if (d != null) return d; } // If this is a DNS name domain, return it here.
var x = req.url.split('/');
if (x.length < 2) return parent.config.domains[''];
var y = parent.config.domains[x[1].toLowerCase()];
if ((y != null) && (y.dns == null)) { return parent.config.domains[x[1].toLowerCase()]; }
return parent.config.domains[''];
}
function handleLogoutRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if (domain.auth == 'sspi') { parent.debug('web', 'handleLogoutRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
// Destroy the user's session to log them out will be re-created next request
if (req.session.userid) {
var user = obj.users[req.session.userid];
if (user != null) { obj.parent.DispatchEvent(['*'], obj, { etype: 'user', userid: user._id, username: user.name, action: 'logout', msg: 'Account logout', domain: domain.id }); }
}
req.session = null;
if (req.query.key != null) { res.redirect(domain.url + '?key=' + req.query.key); } else { res.redirect(domain.url); }
parent.debug('web', 'handleLogoutRequest: success.');
}
// Return true if this user has 2-step auth active
function checkUserOneTimePasswordRequired(domain, user, req) {
// Check if we can skip 2nd factor auth because of the source IP address
if ((req != null) && (req.clientIp != null) && (domain.passwordrequirements != null) && (domain.passwordrequirements.skip2factor != null)) {
for (var i in domain.passwordrequirements.skip2factor) { if (require('ipcheck').match(req.clientIp, domain.passwordrequirements.skip2factor[i]) === true) return false; }
}
// Check if a 2nd factor cookie is present
if (typeof req.headers.cookie == 'string') {
const cookies = req.headers.cookie.split('; ');
for (var i in cookies) {
if (cookies[i].startsWith('twofactor=')) {
var twoFactorCookie = obj.parent.decodeCookie(decodeURIComponent(cookies[i].substring(10)), obj.parent.loginCookieEncryptionKey, (30 * 24 * 60)); // If the cookies does not have an expire feild, assume 30 day timeout.
if ((twoFactorCookie != null) && ((obj.args.cookieipcheck === false) || (twoFactorCookie.ip == null) || (twoFactorCookie.ip === req.clientIp)) && (twoFactorCookie.userid == user._id)) { return false; }
}
}
}
// See if SMS 2FA is available
var sms2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false)) && (parent.smsserver != null) && (user.phone != null));
// Check if a 2nd factor is present
return ((parent.config.settings.no2factorauth !== true) && (sms2fa || (user.otpsecret != null) || ((user.email != null) && (user.emailVerified == true) && (parent.mailserver != null) && (user.otpekey != null)) || ((user.otphkeys != null) && (user.otphkeys.length > 0))));
}
// Check the 2-step auth token
function checkUserOneTimePassword(req, domain, user, token, hwtoken, func) {
parent.debug('web', 'checkUserOneTimePassword()');
const twoStepLoginSupported = ((domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true) && (parent.config.settings.no2factorauth !== true));
if (twoStepLoginSupported == false) { parent.debug('web', 'checkUserOneTimePassword: not supported.'); func(true); return; };
// Check if we can use OTP tokens with email
var otpemail = (parent.mailserver != null);
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.email2factor == false)) { otpemail = false; }
var otpsms = (parent.smsserver != null);
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.sms2factor == false)) { otpsms = false; }
// Check email key
if ((otpemail) && (user.otpekey != null) && (user.otpekey.d != null) && (user.otpekey.k === token)) {
var deltaTime = (Date.now() - user.otpekey.d);
if ((deltaTime > 0) && (deltaTime < 300000)) { // Allow 5 minutes to use the email token (10000 * 60 * 5).
user.otpekey = {};
obj.db.SetUser(user);
parent.debug('web', 'checkUserOneTimePassword: success (email).');
func(true);
return;
}
}
// Check sms key
if ((otpsms) && (user.phone != null) && (user.otpsms != null) && (user.otpsms.d != null) && (user.otpsms.k === token)) {
var deltaTime = (Date.now() - user.otpsms.d);
if ((deltaTime > 0) && (deltaTime < 300000)) { // Allow 5 minutes to use the SMS token (10000 * 60 * 5).
delete user.otpsms;
obj.db.SetUser(user);
parent.debug('web', 'checkUserOneTimePassword: success (SMS).');
func(true);
return;
}
}
// Check hardware key
if (user.otphkeys && (user.otphkeys.length > 0) && (typeof (hwtoken) == 'string') && (hwtoken.length > 0)) {
var authResponse = null;
try { authResponse = JSON.parse(hwtoken); } catch (ex) { }
if ((authResponse != null) && (authResponse.clientDataJSON)) {
// Get all WebAuthn keys
var webAuthnKeys = [];
for (var i = 0; i < user.otphkeys.length; i++) { if (user.otphkeys[i].type == 3) { webAuthnKeys.push(user.otphkeys[i]); } }
if (webAuthnKeys.length > 0) {
// Decode authentication response
var clientAssertionResponse = { response: {} };
clientAssertionResponse.id = authResponse.id;
clientAssertionResponse.rawId = Buffer.from(authResponse.id, 'base64');
clientAssertionResponse.response.authenticatorData = Buffer.from(authResponse.authenticatorData, 'base64');
clientAssertionResponse.response.clientDataJSON = Buffer.from(authResponse.clientDataJSON, 'base64');
clientAssertionResponse.response.signature = Buffer.from(authResponse.signature, 'base64');
clientAssertionResponse.response.userHandle = Buffer.from(authResponse.userHandle, 'base64');
// Look for the key with clientAssertionResponse.id
var webAuthnKey = null;
for (var i = 0; i < webAuthnKeys.length; i++) { if (webAuthnKeys[i].keyId == clientAssertionResponse.id) { webAuthnKey = webAuthnKeys[i]; } }
// If we found a valid key to use, let's validate the response
if (webAuthnKey != null) {
// Figure out the origin
var httpport = ((args.aliasport != null) ? args.aliasport : args.port);
var origin = 'https://' + (domain.dns ? domain.dns : parent.certificates.CommonName);
if (httpport != 443) { origin += ':' + httpport; }
var assertionExpectations = {
challenge: req.session.u2fchallenge,
origin: origin,
factor: 'either',
fmt: 'fido-u2f',
publicKey: webAuthnKey.publicKey,
prevCounter: webAuthnKey.counter,
userHandle: Buffer.from(user._id, 'binary').toString('base64')
};
var webauthnResponse = null;
try { webauthnResponse = obj.webauthn.verifyAuthenticatorAssertionResponse(clientAssertionResponse.response, assertionExpectations); } catch (ex) { parent.debug('web', 'checkUserOneTimePassword: exception ' + ex); console.log(ex); }
if ((webauthnResponse != null) && (webauthnResponse.verified === true)) {
// Update the hardware key counter and accept the 2nd factor
webAuthnKey.counter = webauthnResponse.counter;
obj.db.SetUser(user);
parent.debug('web', 'checkUserOneTimePassword: success (hardware).');
func(true);
} else {
parent.debug('web', 'checkUserOneTimePassword: fail (hardware).');
func(false);
}
return;
}
}
}
}
// Check Google Authenticator
const otplib = require('otplib')
otplib.authenticator.options = { window: 2 }; // Set +/- 1 minute window
if (user.otpsecret && (typeof (token) == 'string') && (token.length == 6) && (otplib.authenticator.check(token, user.otpsecret) == true)) {
parent.debug('web', 'checkUserOneTimePassword: success (authenticator).');
func(true);
return;
};
// Check written down keys
if ((user.otpkeys != null) && (user.otpkeys.keys != null) && (typeof (token) == 'string') && (token.length == 8)) {
var tokenNumber = parseInt(token);
for (var i = 0; i < user.otpkeys.keys.length; i++) {
if ((tokenNumber === user.otpkeys.keys[i].p) && (user.otpkeys.keys[i].u === true)) {
parent.debug('web', 'checkUserOneTimePassword: success (one-time).');
user.otpkeys.keys[i].u = false; func(true); return;
}
}
}
// Check OTP hardware key
if ((domain.yubikey != null) && (domain.yubikey.id != null) && (domain.yubikey.secret != null) && (user.otphkeys != null) && (user.otphkeys.length > 0) && (typeof (token) == 'string') && (token.length == 44)) {
var keyId = token.substring(0, 12);
// Find a matching OTP key
var match = false;
for (var i = 0; i < user.otphkeys.length; i++) { if ((user.otphkeys[i].type === 2) && (user.otphkeys[i].keyid === keyId)) { match = true; } }
// If we have a match, check the OTP
if (match === true) {
var yubikeyotp = require('yubikeyotp');
var request = { otp: token, id: domain.yubikey.id, key: domain.yubikey.secret, timestamp: true }
if (domain.yubikey.proxy) { request.requestParams = { proxy: domain.yubikey.proxy }; }
yubikeyotp.verifyOTP(request, function (err, results) {
if ((results != null) && (results.status == 'OK')) {
parent.debug('web', 'checkUserOneTimePassword: success (Yubikey).');
func(true);
} else {
parent.debug('web', 'checkUserOneTimePassword: fail (Yubikey).');
func(false);
}
});
return;
}
}
parent.debug('web', 'checkUserOneTimePassword: fail (2).');
func(false);
}
// Return a U2F hardware key challenge
function getHardwareKeyChallenge(req, domain, user, func) {
if (req.session.u2fchallenge) { delete req.session.u2fchallenge; };
if (user.otphkeys && (user.otphkeys.length > 0)) {
// Get all WebAuthn keys
var webAuthnKeys = [];
for (var i = 0; i < user.otphkeys.length; i++) { if (user.otphkeys[i].type == 3) { webAuthnKeys.push(user.otphkeys[i]); } }
if (webAuthnKeys.length > 0) {
// Generate a Webauthn challenge, this is really easy, no need to call any modules to do this.
var authnOptions = { type: 'webAuthn', keyIds: [], timeout: 60000, challenge: obj.crypto.randomBytes(64).toString('base64') };
for (var i = 0; i < webAuthnKeys.length; i++) { authnOptions.keyIds.push(webAuthnKeys[i].keyId); }
req.session.u2fchallenge = authnOptions.challenge;
parent.debug('web', 'getHardwareKeyChallenge: success');
func(JSON.stringify(authnOptions));
return;
}
}
parent.debug('web', 'getHardwareKeyChallenge: fail');
func('');
}
function handleLoginRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Check if this is a banned ip address
if (obj.checkAllowLogin(req) == false) {
// Wait and redirect the user
setTimeout(function () {
req.session.messageid = 114; // IP address blocked, try again later.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}, 2000 + (obj.crypto.randomBytes(2).readUInt16BE(0) % 4095));
return;
}
// Normally, use the body username/password. If this is a token, use the username/password in the session.
var xusername = req.body.username, xpassword = req.body.password;
if ((xusername == null) && (xpassword == null) && (req.body.token != null)) { xusername = req.session.tokenusername; xpassword = req.session.tokenpassword; }
// Authenticate the user
obj.authenticate(xusername, xpassword, domain, function (err, userid, passhint) {
if (userid) {
var user = obj.users[userid];
var email2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (parent.mailserver != null) && (user.email != null) && (user.emailVerified == true) && (user.otpekey != null));
var sms2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false)) && (parent.smsserver != null) && (user.phone != null));
// Check if this user has 2-step login active
if ((req.session.loginmode != '6') && checkUserOneTimePasswordRequired(domain, user, req)) {
if ((req.body.hwtoken == '**email**') && email2fa) {
user.otpekey = { k: obj.common.zeroPad(getRandomEightDigitInteger(), 8), d: Date.now() };
obj.db.SetUser(user);
parent.debug('web', 'Sending 2FA email to: ' + user.email);
parent.mailserver.sendAccountLoginMail(domain, user.email, user.otpekey.k, obj.getLanguageCodes(req));
req.session.messageid = 2; // "Email sent" message
req.session.loginmode = '4';
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
if ((req.body.hwtoken == '**sms**') && sms2fa) {
// Cause a token to be sent to the user's phone number
user.otpsms = { k: obj.common.zeroPad(getRandomSixDigitInteger(), 6), d: Date.now() };
obj.db.SetUser(user);
parent.debug('web', 'Sending 2FA SMS to: ' + user.phone);
parent.smsserver.sendToken(domain, user.phone, user.otpsms.k, obj.getLanguageCodes(req));
// Ask for a login token & confirm sms was sent
req.session.messageid = 4; // "SMS sent" message
req.session.loginmode = '4';
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
checkUserOneTimePassword(req, domain, user, req.body.token, req.body.hwtoken, function (result) {
if (result == false) {
var randomWaitTime = 0;
// 2-step auth is required, but the token is not present or not valid.
if ((req.body.token != null) || (req.body.hwtoken != null)) {
randomWaitTime = 2000 + (obj.crypto.randomBytes(2).readUInt16BE(0) % 4095); // This is a fail, wait a random time. 2 to 6 seconds.
req.session.messageid = 108; // Invalid token, try again.
if (obj.parent.authlog) { obj.parent.authLog('https', 'Failed 2FA for ' + xusername + ' from ' + cleanRemoteAddr(req.clientIp) + ' port ' + req.port); }
parent.debug('web', 'handleLoginRequest: invalid 2FA token');
obj.parent.DispatchEvent(['*', 'server-users', 'user/' + domain.id + '/' + user.name], obj, { action: 'authfail', username: user.name, userid: 'user/' + domain.id + '/' + user.name, domain: domain.id, msg: 'User login attempt with incorrect 2nd factor from ' + req.clientIp });
obj.setbadLogin(req);
} else {
parent.debug('web', 'handleLoginRequest: 2FA token required');
}
// Wait and redirect the user
setTimeout(function () {
req.session.loginmode = '4';
req.session.tokenemail = ((user.email != null) && (user.emailVerified == true) && (parent.mailserver != null) && (user.otpekey != null));
req.session.tokensms = ((user.phone != null) && (parent.smsserver != null));
req.session.tokenuserid = userid;
req.session.tokenusername = xusername;
req.session.tokenpassword = xpassword;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}, randomWaitTime);
} else {
// Check if we need to remember this device
if ((req.body.remembertoken === 'on') && ((domain.twofactorcookiedurationdays == null) || (domain.twofactorcookiedurationdays > 0))) {
var maxCookieAge = domain.twofactorcookiedurationdays;
if (typeof maxCookieAge != 'number') { maxCookieAge = 30; }
console.log('maxCookieAge', maxCookieAge);
const twoFactorCookie = obj.parent.encodeCookie({ userid: user._id, expire: maxCookieAge * 24 * 60 /*, ip: req.clientIp*/ }, obj.parent.loginCookieEncryptionKey);
res.cookie('twofactor', twoFactorCookie, { maxAge: (maxCookieAge * 24 * 60 * 60 * 1000), httpOnly: true, sameSite: 'strict', secure: true });
}
// Check if email address needs to be confirmed
var emailcheck = ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true) && (domain.auth != 'sspi') && (domain.auth != 'ldap'))
if (emailcheck && (user.emailVerified !== true)) {
parent.debug('web', 'Redirecting using ' + user.name + ' to email check login page');
req.session.messageid = 3; // "Email verification required" message
req.session.loginmode = '7';
req.session.passhint = user.email;
req.session.cuserid = userid;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Login successful
if (obj.parent.authlog) { obj.parent.authLog('https', 'Accepted password for ' + xusername + ' from ' + req.clientIp + ' port ' + req.connection.remotePort); }
parent.debug('web', 'handleLoginRequest: successful 2FA login');
completeLoginRequest(req, res, domain, user, userid, xusername, xpassword, direct);
}
});
return;
}
// Check if email address needs to be confirmed
var emailcheck = ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true) && (domain.auth != 'sspi') && (domain.auth != 'ldap'))
if (emailcheck && (user.emailVerified !== true)) {
parent.debug('web', 'Redirecting using ' + user.name + ' to email check login page');
req.session.messageid = 3; // "Email verification required" message
req.session.loginmode = '7';
req.session.passhint = user.email;
req.session.cuserid = userid;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Login successful
if (obj.parent.authlog) { obj.parent.authLog('https', 'Accepted password for ' + xusername + ' from ' + req.clientIp + ' port ' + req.connection.remotePort); }
parent.debug('web', 'handleLoginRequest: successful login');
completeLoginRequest(req, res, domain, user, userid, xusername, xpassword, direct);
} else {
// Login failed, log the error
if (obj.parent.authlog) { obj.parent.authLog('https', 'Failed password for ' + xusername + ' from ' + req.clientIp + ' port ' + req.connection.remotePort); }
// Wait a random delay
setTimeout(function () {
// If the account is locked, display that.
if (typeof xusername == 'string') {
var xuserid = 'user/' + domain.id + '/' + xusername.toLowerCase();
if (err == 'locked') {
parent.debug('web', 'handleLoginRequest: login failed, locked account');
req.session.messageid = 110; // Account locked.
obj.parent.DispatchEvent(['*', 'server-users', xuserid], obj, { action: 'authfail', userid: xuserid, username: xusername, domain: domain.id, msg: 'User login attempt on locked account from ' + req.clientIp });
obj.setbadLogin(req);
} else {
parent.debug('web', 'handleLoginRequest: login failed, bad username and password');
req.session.messageid = 112; // Login failed, check username and password.
obj.parent.DispatchEvent(['*', 'server-users', xuserid], obj, { action: 'authfail', userid: xuserid, username: xusername, domain: domain.id, msg: 'Invalid user login attempt from ' + req.clientIp });
obj.setbadLogin(req);
}
}
// Clean up login mode and display password hint if present.
delete req.session.loginmode;
if ((passhint != null) && (passhint.length > 0)) {
req.session.passhint = passhint;
} else {
delete req.session.passhint;
}
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}, 2000 + (obj.crypto.randomBytes(2).readUInt16BE(0) % 4095)); // Wait for 2 to ~6 seconds.
}
});
}
function completeLoginRequest(req, res, domain, user, userid, xusername, xpassword, direct) {
// Check if we need to change the password
if ((typeof user.passchange == 'number') && ((user.passchange == -1) || ((typeof domain.passwordrequirements == 'object') && (typeof domain.passwordrequirements.reset == 'number') && (user.passchange + (domain.passwordrequirements.reset * 86400) < Math.floor(Date.now() / 1000))))) {
// Request a password change
parent.debug('web', 'handleLoginRequest: login ok, password change requested');
req.session.loginmode = '6';
req.session.messageid = 113; // Password change requested.
req.session.resettokenuserid = userid;
req.session.resettokenusername = xusername;
req.session.resettokenpassword = xpassword;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Save login time
user.pastlogin = user.login;
user.login = Math.floor(Date.now() / 1000);
obj.db.SetUser(user);
// Notify account login
var targets = ['*', 'server-users'];
if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
obj.parent.DispatchEvent(targets, obj, { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'login', msg: 'Account login', domain: domain.id });
// Regenerate session when signing in to prevent fixation
//req.session.regenerate(function () {
// Store the user's primary key in the session store to be retrieved, or in this case the entire user object
delete req.session.loginmode;
delete req.session.tokenuserid;
delete req.session.tokenusername;
delete req.session.tokenpassword;
delete req.session.tokenemail;
delete req.session.tokensms;
delete req.session.messageid;
delete req.session.passhint;
delete req.session.cuserid;
req.session.userid = userid;
req.session.domainid = domain.id;
req.session.currentNode = '';
req.session.ip = req.clientIp;
if (req.body.viewmode) { req.session.viewmode = req.body.viewmode; }
if (req.body.host) {
// TODO: This is a terrible search!!! FIX THIS.
/*
obj.db.GetAllType('node', function (err, docs) {
for (var i = 0; i < docs.length; i++) {
if (docs[i].name == req.body.host) {
req.session.currentNode = docs[i]._id;
break;
}
}
console.log("CurrentNode: " + req.session.currentNode);
// This redirect happens after finding node is completed
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
});
*/
parent.debug('web', 'handleLoginRequest: login ok (1)');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); } // Temporary
} else {
parent.debug('web', 'handleLoginRequest: login ok (2)');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
//});
}
function handleCreateAccountRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { parent.debug('web', 'handleCreateAccountRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Always lowercase the email address
if (req.body.email) { req.body.email = req.body.email.toLowerCase(); }
// If the email is the username, set this here.
if (domain.usernameisemail) { req.body.username = req.body.email; }
// Accounts that start with ~ are not allowed
if ((typeof req.body.username != 'string') || (req.body.username.length < 1) || (req.body.username[0] == '~')) {
parent.debug('web', 'handleCreateAccountRequest: unable to create account (0)');
req.session.loginmode = '2';
req.session.messageid = 100; // Unable to create account.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Count the number of users in this domain
var domainUserCount = 0;
for (var i in obj.users) { if (obj.users[i].domain == domain.id) { domainUserCount++; } }
// Check if we are allowed to create new users using the login screen
if ((domain.newaccounts !== 1) && (domain.newaccounts !== true) && (domainUserCount > 0)) {
parent.debug('web', 'handleCreateAccountRequest: domainUserCount > 1.');
res.sendStatus(401);
return;
}
// Check if this request is for an allows email domain
if ((domain.newaccountemaildomains != null) && Array.isArray(domain.newaccountemaildomains)) {
var i = -1;
if (typeof req.body.email == 'string') { i = req.body.email.indexOf('@'); }
if (i == -1) {
parent.debug('web', 'handleCreateAccountRequest: unable to create account (1)');
req.session.loginmode = '2';
req.session.messageid = 100; // Unable to create account.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
var emailok = false, emaildomain = req.body.email.substring(i + 1).toLowerCase();
for (var i in domain.newaccountemaildomains) { if (emaildomain == domain.newaccountemaildomains[i].toLowerCase()) { emailok = true; } }
if (emailok == false) {
parent.debug('web', 'handleCreateAccountRequest: unable to create account (2)');
req.session.loginmode = '2';
req.session.messageid = 100; // Unable to create account.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
}
// Check if we exceed the maximum number of user accounts
obj.db.isMaxType(domain.limits.maxuseraccounts, 'user', domain.id, function (maxExceed) {
if (maxExceed) {
parent.debug('web', 'handleCreateAccountRequest: account limit reached');
req.session.loginmode = '2';
req.session.messageid = 101; // Account limit reached.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
if (!obj.common.validateUsername(req.body.username, 1, 64) || !obj.common.validateEmail(req.body.email, 1, 256) || !obj.common.validateString(req.body.password1, 1, 256) || !obj.common.validateString(req.body.password2, 1, 256) || (req.body.password1 != req.body.password2) || req.body.username == '~' || !obj.common.checkPasswordRequirements(req.body.password1, domain.passwordrequirements)) {
parent.debug('web', 'handleCreateAccountRequest: unable to create account (3)');
req.session.loginmode = '2';
req.session.messageid = 100; // Unable to create account.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
// Check if this email was already verified
obj.db.GetUserWithVerifiedEmail(domain.id, req.body.email, function (err, docs) {
if (docs.length > 0) {
parent.debug('web', 'handleCreateAccountRequest: Existing account with this email address');
req.session.loginmode = '2';
req.session.messageid = 102; // Existing account with this email address.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
// Check if there is domain.newAccountToken, check if supplied token is valid
if ((domain.newaccountspass != null) && (domain.newaccountspass != '') && (req.body.anewaccountpass != domain.newaccountspass)) {
parent.debug('web', 'handleCreateAccountRequest: Invalid account creation token');
req.session.loginmode = '2';
req.session.messageid = 103; // Invalid account creation token.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Check if user exists
if (obj.users['user/' + domain.id + '/' + req.body.username.toLowerCase()]) {
parent.debug('web', 'handleCreateAccountRequest: Username already exists');
req.session.loginmode = '2';
req.session.messageid = 104; // Username already exists.
} else {
var user = { type: 'user', _id: 'user/' + domain.id + '/' + req.body.username.toLowerCase(), name: req.body.username, email: req.body.email, creation: Math.floor(Date.now() / 1000), login: Math.floor(Date.now() / 1000), domain: domain.id };
if (domain.newaccountsrights) { user.siteadmin = domain.newaccountsrights; }
if (obj.common.validateStrArray(domain.newaccountrealms)) { user.groups = domain.newaccountrealms; }
if ((domain.passwordrequirements != null) && (domain.passwordrequirements.hint === true) && (req.body.apasswordhint)) { var hint = req.body.apasswordhint; if (hint.length > 250) { hint = hint.substring(0, 250); } user.passhint = hint; }
if (domainUserCount == 0) { user.siteadmin = 4294967295; /*if (domain.newaccounts === 2) { delete domain.newaccounts; }*/ } // If this is the first user, give the account site admin.
// Auto-join any user groups
if (typeof domain.newaccountsusergroups == 'object') {
for (var i in domain.newaccountsusergroups) {
var ugrpid = domain.newaccountsusergroups[i];
if (ugrpid.indexOf('/') < 0) { ugrpid = 'ugrp/' + domain.id + '/' + ugrpid; }
var ugroup = obj.userGroups[ugrpid];
if (ugroup != null) {
// Add group to the user
if (user.links == null) { user.links = {}; }
user.links[ugroup._id] = { rights: 1 };
// Add user to the group
ugroup.links[user._id] = { userid: user._id, name: user.name, rights: 1 };
db.Set(ugroup);
// Notify user group change
var event = { etype: 'ugrp', ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msg: 'Added user ' + user.name + ' to user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user._id], obj, event);
}
}
}
obj.users[user._id] = user;
req.session.userid = user._id;
req.session.domainid = domain.id;
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
// Create a user, generate a salt and hash the password
require('./pass').hash(req.body.password1, function (err, salt, hash, tag) {
if (err) throw err;
user.salt = salt;
user.hash = hash;
delete user.passtype;
obj.db.SetUser(user);
// Send the verification email
if ((obj.parent.mailserver != null) && (domain.auth != 'sspi') && (domain.auth != 'ldap') && (obj.common.validateEmail(user.email, 1, 256) == true)) { obj.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email, obj.getLanguageCodes(req)); }
}, 0);
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountcreate', msg: 'Account created, email is ' + req.body.email, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users'], obj, event);
}
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
});
}
}
});
}
// Called to process an account password reset
function handleResetPasswordRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Check everything is ok
if ((domain == null) || (domain.auth == 'sspi') || (domain.auth == 'ldap') || (typeof req.body.rpassword1 != 'string') || (typeof req.body.rpassword2 != 'string') || (req.body.rpassword1 != req.body.rpassword2) || (typeof req.body.rpasswordhint != 'string') || (req.session == null) || (typeof req.session.resettokenusername != 'string') || (typeof req.session.resettokenpassword != 'string')) {
parent.debug('web', 'handleResetPasswordRequest: checks failed');
delete req.session.loginmode;
delete req.session.tokenuserid;
delete req.session.tokenusername;
delete req.session.tokenpassword;
delete req.session.resettokenuserid;
delete req.session.resettokenusername;
delete req.session.resettokenpassword;
delete req.session.tokenemail;
delete req.session.tokensms;
delete req.session.messageid;
delete req.session.passhint;
delete req.session.cuserid;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Authenticate the user
obj.authenticate(req.session.resettokenusername, req.session.resettokenpassword, domain, function (err, userid, passhint) {
if (userid) {
// Login
var user = obj.users[userid];
// If we have password requirements, check this here.
if (!obj.common.checkPasswordRequirements(req.body.rpassword1, domain.passwordrequirements)) {
parent.debug('web', 'handleResetPasswordRequest: password rejected, use a different one (1)');
req.session.loginmode = '6';
req.session.messageid = 105; // Password rejected, use a different one.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Check if the password is the same as a previous one
obj.checkOldUserPasswords(domain, user, req.body.rpassword1, function (result) {
if (result != 0) {
// This is the same password as an older one, request a password change again
parent.debug('web', 'handleResetPasswordRequest: password rejected, use a different one (2)');
req.session.loginmode = '6';
req.session.messageid = 105; // Password rejected, use a different one.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
// Update the password, use a different salt.
require('./pass').hash(req.body.rpassword1, function (err, salt, hash, tag) {
const nowSeconds = Math.floor(Date.now() / 1000);
if (err) { parent.debug('web', 'handleResetPasswordRequest: hash error.'); throw err; }
if (domain.passwordrequirements != null) {
// Save password hint if this feature is enabled
if ((domain.passwordrequirements.hint === true) && (req.body.apasswordhint)) { var hint = req.body.apasswordhint; if (hint.length > 250) hint = hint.substring(0, 250); user.passhint = hint; } else { delete user.passhint; }
// Save previous password if this feature is enabled
if ((typeof domain.passwordrequirements.oldpasswordban == 'number') && (domain.passwordrequirements.oldpasswordban > 0)) {
if (user.oldpasswords == null) { user.oldpasswords = []; }
user.oldpasswords.push({ salt: user.salt, hash: user.hash, start: user.passchange, end: nowSeconds });
const extraOldPasswords = user.oldpasswords.length - domain.passwordrequirements.oldpasswordban;
if (extraOldPasswords > 0) { user.oldpasswords.splice(0, extraOldPasswords); }
}
}
user.salt = salt;
user.hash = hash;
user.passchange = nowSeconds;
delete user.passtype;
obj.db.SetUser(user);
// Event the account change
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: 'User password reset', domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
// Login successful
parent.debug('web', 'handleResetPasswordRequest: success');
req.session.userid = userid;
req.session.domainid = domain.id;
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
completeLoginRequest(req, res, domain, obj.users[userid], userid, req.session.tokenusername, req.session.tokenpassword, direct);
}, 0);
}
}, 0);
} else {
// Failed, error out.
parent.debug('web', 'handleResetPasswordRequest: failed authenticate()');
delete req.session.loginmode;
delete req.session.tokenuserid;
delete req.session.tokenusername;
delete req.session.tokenpassword;
delete req.session.resettokenuserid;
delete req.session.resettokenusername;
delete req.session.resettokenpassword;
delete req.session.tokenemail;
delete req.session.tokensms;
delete req.session.messageid;
delete req.session.passhint;
delete req.session.cuserid;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
});
}
// Called to process an account reset request
function handleResetAccountRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.auth == 'sspi') || (domain.auth == 'ldap') || (obj.args.lanonly == true) || (obj.parent.certificates.CommonName == null) || (obj.parent.certificates.CommonName.indexOf('.') == -1)) { parent.debug('web', 'handleResetAccountRequest: check failed'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Always lowercase the email address
if (req.body.email) { req.body.email = req.body.email.toLowerCase(); }
// Get the email from the body or session.
var email = req.body.email;
if ((email == null) || (email == '')) { email = req.session.tokenemail; }
// Check the email string format
if (!email || checkEmail(email) == false) {
parent.debug('web', 'handleResetAccountRequest: Invalid email');
req.session.loginmode = '3';
req.session.messageid = 106; // Invalid email.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
obj.db.GetUserWithVerifiedEmail(domain.id, email, function (err, docs) {
if ((err != null) || (docs.length == 0)) {
parent.debug('web', 'handleResetAccountRequest: Account not found');
req.session.loginmode = '3';
req.session.messageid = 1; // If valid, reset mail sent. Instead of "Account not found" (107), we send this hold on message so users can't know if this account exists or not.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
// If many accounts have the same validated e-mail, we are going to use the first one for display, but sent a reset email for all accounts.
var responseSent = false;
for (var i in docs) {
var user = docs[i];
if (checkUserOneTimePasswordRequired(domain, user, req) == true) {
// Second factor setup, request it now.
checkUserOneTimePassword(req, domain, user, req.body.token, req.body.hwtoken, function (result) {
if (result == false) {
if (i == 0) {
// 2-step auth is required, but the token is not present or not valid.
parent.debug('web', 'handleResetAccountRequest: Invalid 2FA token, try again');
if ((req.body.token != null) || (req.body.hwtoken != null)) {
req.session.messageid = 108; // Invalid token, try again.
obj.parent.DispatchEvent(['*', 'server-users', 'user/' + domain.id + '/' + user.name], obj, { action: 'authfail', username: user.name, userid: 'user/' + domain.id + '/' + user.name, domain: domain.id, msg: 'User login attempt with incorrect 2nd factor from ' + req.clientIp });
obj.setbadLogin(req);
}
req.session.loginmode = '5';
req.session.tokenemail = email;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
} else {
// Send email to perform recovery.
delete req.session.tokenemail;
if (obj.parent.mailserver != null) {
obj.parent.mailserver.sendAccountResetMail(domain, user.name, user.email, obj.getLanguageCodes(req));
if (i == 0) {
parent.debug('web', 'handleResetAccountRequest: Hold on, reset mail sent.');
req.session.loginmode = '1';
req.session.messageid = 1; // If valid, reset mail sent.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
} else {
if (i == 0) {
parent.debug('web', 'handleResetAccountRequest: Unable to sent email.');
req.session.loginmode = '3';
req.session.messageid = 109; // Unable to sent email.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
}
}
});
} else {
// No second factor, send email to perform recovery.
if (obj.parent.mailserver != null) {
obj.parent.mailserver.sendAccountResetMail(domain, user.name, user.email, obj.getLanguageCodes(req));
if (i == 0) {
parent.debug('web', 'handleResetAccountRequest: Hold on, reset mail sent.');
req.session.loginmode = '1';
req.session.messageid = 1; // If valid, reset mail sent.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
} else {
if (i == 0) {
parent.debug('web', 'handleResetAccountRequest: Unable to sent email.');
req.session.loginmode = '3';
req.session.messageid = 109; // Unable to sent email.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
}
}
}
}
});
}
}
// Handle account email change and email verification request
function handleCheckAccountEmailRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((obj.parent.mailserver == null) || (domain.auth == 'sspi') || (domain.auth == 'ldap') || (typeof req.session.cuserid != 'string') || (obj.users[req.session.cuserid] == null) || (!obj.common.validateEmail(req.body.email, 1, 256))) { parent.debug('web', 'handleCheckAccountEmailRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Always lowercase the email address
if (req.body.email) { req.body.email = req.body.email.toLowerCase(); }
// Get the email from the body or session.
var email = req.body.email;
if ((email == null) || (email == '')) { email = req.session.tokenemail; }
// Check if this request is for an allows email domain
if ((domain.newaccountemaildomains != null) && Array.isArray(domain.newaccountemaildomains)) {
var i = -1;
if (typeof req.body.email == 'string') { i = req.body.email.indexOf('@'); }
if (i == -1) {
parent.debug('web', 'handleCreateAccountRequest: unable to create account (1)');
req.session.loginmode = '7';
req.session.messageid = 106; // Invalid email.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
var emailok = false, emaildomain = req.body.email.substring(i + 1).toLowerCase();
for (var i in domain.newaccountemaildomains) { if (emaildomain == domain.newaccountemaildomains[i].toLowerCase()) { emailok = true; } }
if (emailok == false) {
parent.debug('web', 'handleCreateAccountRequest: unable to create account (2)');
req.session.loginmode = '7';
req.session.messageid = 106; // Invalid email.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
}
// Check the email string format
if (!email || checkEmail(email) == false) {
parent.debug('web', 'handleCheckAccountEmailRequest: Invalid email');
req.session.loginmode = '7';
req.session.messageid = 106; // Invalid email.
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
// Check is email already exists
obj.db.GetUserWithVerifiedEmail(domain.id, email, function (err, docs) {
if ((err != null) || (docs.length > 0)) {
// Email already exitst
req.session.messageid = 102; // Existing account with this email address.
} else {
// Update the user and notify of user email address change
var user = obj.users[req.session.cuserid];
if (user.email != email) {
user.email = email;
db.SetUser(user);
var targets = ['*', 'server-users', user._id];
if (user.groups) { for (var i in user.groups) { targets.push('server-users:' + i); } }
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: 'Account changed: ' + user.name, domain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
parent.DispatchEvent(targets, obj, event);
}
// Send the verification email
obj.parent.mailserver.sendAccountCheckMail(domain, user.name, user.email, obj.getLanguageCodes(req));
// Send the response
req.session.messageid = 2; // Email sent.
}
req.session.loginmode = '7';
delete req.session.cuserid;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
});
}
}
// Called to process a web based email verification request
function handleCheckMailRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.auth == 'sspi') || (domain.auth == 'ldap') || (obj.parent.mailserver == null)) { parent.debug('web', 'handleCheckMailRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if (req.query.c != null) {
var cookie = obj.parent.decodeCookie(req.query.c, obj.parent.mailserver.mailCookieEncryptionKey, 30);
if ((cookie != null) && (cookie.u != null) && (cookie.e != null)) {
var idsplit = cookie.u.split('/');
if ((idsplit.length != 2) || (idsplit[0] != domain.id)) {
parent.debug('web', 'handleCheckMailRequest: Invalid domain.');
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 1, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27') }, req, domain));
} else {
obj.db.Get('user/' + cookie.u.toLowerCase(), function (err, docs) {
if (docs.length == 0) {
parent.debug('web', 'handleCheckMailRequest: Invalid username.');
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 2, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: encodeURIComponent(idsplit[1]).replace(/'/g, '%27') }, req, domain));
} else {
var user = docs[0];
if (user.email != cookie.e) {
parent.debug('web', 'handleCheckMailRequest: Invalid e-mail.');
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 3, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: encodeURIComponent(user.email).replace(/'/g, '%27'), arg2: encodeURIComponent(user.name).replace(/'/g, '%27') }, req, domain));
} else {
if (cookie.a == 1) {
// Account email verification
if (user.emailVerified == true) {
parent.debug('web', 'handleCheckMailRequest: email already verified.');
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 4, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: encodeURIComponent(user.email).replace(/'/g, '%27'), arg2: encodeURIComponent(user.name).replace(/'/g, '%27') }, req, domain));
} else {
obj.db.GetUserWithVerifiedEmail(domain.id, user.email, function (err, docs) {
if (docs.length > 0) {
parent.debug('web', 'handleCheckMailRequest: email already in use.');
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 5, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: encodeURIComponent(user.email).replace(/'/g, '%27') }, req, domain));
} else {
parent.debug('web', 'handleCheckMailRequest: email verification success.');
// Set the verified flag
obj.users[user._id].emailVerified = true;
user.emailVerified = true;
obj.db.SetUser(user);
// Event the change
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: 'Verified email of user ' + EscapeHtml(user.name) + ' (' + EscapeHtml(user.email) + ')', domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
// Send the confirmation page
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 6, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: encodeURIComponent(user.email).replace(/'/g, '%27'), arg2: encodeURIComponent(user.name).replace(/'/g, '%27') }, req, domain));
// Send a notification
obj.parent.DispatchEvent([user._id], obj, { action: 'notify', title: 'Email verified', value: user.email, nolog: 1, id: Math.random() });
// Send to authlog
if (obj.parent.authlog) { obj.parent.authLog('https', 'Verified email address ' + user.email + ' for user ' + user.name); }
}
});
}
} else if (cookie.a == 2) {
// Account reset
if (user.emailVerified != true) {
parent.debug('web', 'handleCheckMailRequest: email not verified.');
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 7, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: EscapeHtml(user.email), arg2: EscapeHtml(user.name) }, req, domain));
} else {
// Set a temporary password
obj.crypto.randomBytes(16, function (err, buf) {
var newpass = buf.toString('base64').split('=').join('').split('/').join('');
require('./pass').hash(newpass, function (err, salt, hash, tag) {
var userinfo = null;
if (err) throw err;
// Change the password
userinfo = obj.users[user._id];
userinfo.salt = salt;
userinfo.hash = hash;
delete userinfo.passtype;
userinfo.passchange = Math.floor(Date.now() / 1000);
delete userinfo.passhint;
//delete userinfo.otpsecret; // Currently a email password reset will turn off 2-step login.
obj.db.SetUser(userinfo);
// Event the change
var event = { etype: 'user', userid: user._id, username: userinfo.name, account: obj.CloneSafeUser(userinfo), action: 'accountchange', msg: 'Password reset for user ' + EscapeHtml(user.name), domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users', user._id], obj, event);
// Send the new password
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 8, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), arg1: EscapeHtml(user.name), arg2: EscapeHtml(newpass) }, req, domain));
parent.debug('web', 'handleCheckMailRequest: send temporary password.');
// Send to authlog
if (obj.parent.authlog) { obj.parent.authLog('https', 'Performed account reset for user ' + user.name); }
}, 0);
});
}
} else {
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 9, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27') }, req, domain));
}
}
}
});
}
} else {
render(req, res, getRenderPage('message', req, domain), getRenderArgs({ titleid: 1, msgid: 10, domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27') }, req, domain));
}
}
}
// Called to process an agent invite GET/POST request
function handleInviteRequest(req, res) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'handleInviteRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((req.body.inviteCode == null) || (req.body.inviteCode == '')) { render(req, res, getRenderPage('invite', req, domain), getRenderArgs({ messageid: 0 }, req, domain)); return; } // No invitation code
// Each for a device group that has this invite code.
for (var i in obj.meshes) {
if ((obj.meshes[i].domain == domain.id) && (obj.meshes[i].invite != null) && (obj.meshes[i].invite.codes.indexOf(req.body.inviteCode) >= 0)) {
// Send invitation link, valid for 1 minute.
res.redirect(domain.url + 'agentinvite?c=' + parent.encodeCookie({ a: 4, mid: i, f: obj.meshes[i].invite.flags, expire: 1 }, parent.invitationLinkEncryptionKey) + (req.query.key ? ('&key=' + req.query.key) : ''));
return;
}
}
render(req, res, getRenderPage('invite', req, domain), getRenderArgs({ messageid: 100 }, req, domain)); // Bad invitation code
}
// Called to render the MSTSC (RDP) web page
function handleMSTSCRequest(req, res) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'handleMSTSCRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if (req.query.ws != null) {
// This is a query with a websocket relay cookie, check that the cookie is valid and use it.
var rcookie = parent.decodeCookie(req.query.ws, parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
if ((rcookie != null) && (rcookie.domainid == domain.id) && (rcookie.nodeid != null) && (rcookie.tcpport != null)) {
render(req, res, getRenderPage('mstsc', req, domain), getRenderArgs({ cookie: req.query.ws, name: encodeURIComponent(req.query.name).replace(/'/g, '%27') }, req, domain)); return;
}
}
// Get the logged in user if present
var user = null;
// If there is a login token, use that
if (req.query.login != null) {
var ucookie = parent.decodeCookie(req.query.login, parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
if ((ucookie != null) && (ucookie.a === 3) && (typeof ucookie.u == 'string')) { user = obj.users[ucookie.u]; }
}
// If no token, see if we have an active session
if ((user == null) && (req.session.userid != null)) { user = obj.users[req.session.userid]; }
// If still no user, see if we have a default user
if ((user == null) && (obj.args.user)) { user = obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]; }
// No user login, exit now
if (user == null) { res.sendStatus(401); return; }
// Check the nodeid
if (req.query.node != null) {
var nodeidsplit = req.query.node.split('/');
if (nodeidsplit.length == 1) {
req.query.node = 'node/' + domain.id + '/' + nodeidsplit[0]; // Format the nodeid correctly
} else if (nodeidsplit.length == 3) {
if ((nodeidsplit[0] != 'node') || (nodeidsplit[1] != domain.id)) { req.query.node = null; } // Check the nodeid format
} else {
req.query.node = null; // Bad nodeid
}
}
// If there is no nodeid, exit now
if (req.query.node == null) { render(req, res, getRenderPage('mstsc', req, domain), getRenderArgs({ cookie: '', name: '' }, req, domain)); return; }
// Fetch the node from the database
obj.db.Get(req.query.node, function (err, nodes) {
if ((err != null) || (nodes.length != 1)) { res.sendStatus(404); return; }
const node = nodes[0];
// Check access rights, must have remote control rights
if ((obj.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0) { res.sendStatus(401); return; }
// Figure out the target port
var port = 3389;
if (typeof node.rdpport == 'number') { port = node.rdpport; }
if (req.query.port != null) { var qport = 0; try { qport = parseInt(req.query.port); } catch (ex) { } if ((typeof qport == 'number') && (qport > 0) && (qport < 65536)) { port = qport; } }
// Generate a cookie and respond
var cookie = parent.encodeCookie({ userid: user._id, domainid: user.domain, nodeid: node._id, tcpport: port }, parent.loginCookieEncryptionKey);
render(req, res, getRenderPage('mstsc', req, domain), getRenderArgs({ cookie: cookie, name: encodeURIComponent(node.name).replace(/'/g, '%27') }, req, domain));
});
}
// Called to process an agent invite request
function handleAgentInviteRequest(req, res) {
const domain = getDomain(req);
if ((domain == null) || ((req.query.m == null) && (req.query.c == null))) { parent.debug('web', 'handleAgentInviteRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if (req.query.c != null) {
// A cookie is specified in the query string, use that
var cookie = obj.parent.decodeCookie(req.query.c, obj.parent.invitationLinkEncryptionKey);
if (cookie == null) { res.sendStatus(404); return; }
var mesh = obj.meshes[cookie.mid];
if (mesh == null) { res.sendStatus(404); return; }
var installflags = cookie.f;
if (typeof installflags != 'number') { installflags = 0; }
parent.debug('web', 'handleAgentInviteRequest using cookie.');
var meshcookie = parent.encodeCookie({ m: mesh._id.split('/')[2] }, parent.invitationLinkEncryptionKey);
render(req, res, getRenderPage('agentinvite', req, domain), getRenderArgs({ meshid: meshcookie, serverport: ((args.aliasport != null) ? args.aliasport : args.port), serverhttps: ((args.notls == true) ? '0' : '1'), servernoproxy: ((domain.agentnoproxy === true) ? '1' : '0'), meshname: encodeURIComponent(mesh.name).replace(/'/g, '%27'), installflags: installflags }, req, domain));
} else if (req.query.m != null) {
// The MeshId is specified in the query string, use that
var mesh = obj.meshes['mesh/' + domain.id + '/' + req.query.m.toLowerCase()];
if (mesh == null) { res.sendStatus(404); return; }
var installflags = 0;
if (req.query.f) { installflags = parseInt(req.query.f); }
if (typeof installflags != 'number') { installflags = 0; }
parent.debug('web', 'handleAgentInviteRequest using meshid.');
var meshcookie = parent.encodeCookie({ m: mesh._id.split('/')[2] }, parent.invitationLinkEncryptionKey);
render(req, res, getRenderPage('agentinvite', req, domain), getRenderArgs({ meshid: meshcookie, serverport: ((args.aliasport != null) ? args.aliasport : args.port), serverhttps: ((args.notls == true) ? '0' : '1'), servernoproxy: ((domain.agentnoproxy === true) ? '1' : '0'), meshname: encodeURIComponent(mesh.name).replace(/'/g, '%27'), installflags: installflags }, req, domain));
}
}
function handleDeleteAccountRequest(req, res, direct) {
parent.debug('web', 'handleDeleteAccountRequest()');
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { parent.debug('web', 'handleDeleteAccountRequest: failed checks.'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
var user = null;
if (req.body.authcookie) {
// If a authentication cookie is provided, decode it here
var loginCookie = obj.parent.decodeCookie(req.body.authcookie, obj.parent.loginCookieEncryptionKey, 60); // 60 minute timeout
if ((loginCookie != null) && (domain.id == loginCookie.domainid)) { user = obj.users[loginCookie.userid]; }
} else {
// Check if the user is logged and we have all required parameters
if (!req.session || !req.session.userid || !req.body.apassword1 || (req.body.apassword1 != req.body.apassword2) || (req.session.domainid != domain.id)) {
parent.debug('web', 'handleDeleteAccountRequest: required parameters not present.');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
} else {
user = obj.users[req.session.userid];
}
}
if (!user) { parent.debug('web', 'handleDeleteAccountRequest: user not found.'); res.sendStatus(404); return; }
if ((user.siteadmin != 0xFFFFFFFF) && ((user.siteadmin & 1024) != 0)) { parent.debug('web', 'handleDeleteAccountRequest: account settings locked.'); res.sendStatus(404); return; }
// Check if the password is correct
obj.authenticate(user._id.split('/')[2], req.body.apassword1, domain, function (err, userid) {
var deluser = obj.users[userid];
if ((userid != null) && (deluser != null)) {
// Remove all links to this user
if (deluser.links != null) {
for (var i in deluser.links) {
if (i.startsWith('mesh/')) {
// Get the device group
var mesh = obj.meshes[i];
if (mesh) {
// Remove user from the mesh
if (mesh.links[deluser._id] != null) { delete mesh.links[deluser._id]; parent.db.Set(mesh); }
// Notify mesh change
var change = 'Removed user ' + deluser.name + ' from group ' + mesh.name;
var event = { etype: 'mesh', userid: user._id, username: user.name, meshid: mesh._id, name: mesh.name, mtype: mesh.mtype, desc: mesh.desc, action: 'meshchange', links: mesh.links, msg: change, domain: domain.id, invite: mesh.invite };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the mesh. Another event will come.
parent.DispatchEvent(['*', mesh._id, deluser._id, user._id], obj, event);
}
} else if (i.startsWith('node/')) {
// Get the node and the rights for this node
obj.GetNodeWithRights(domain, deluser, i, function (node, rights, visible) {
if ((node == null) || (node.links == null) || (node.links[deluser._id] == null)) return;
// Remove the link and save the node to the database
delete node.links[deluser._id];
if (Object.keys(node.links).length == 0) { delete node.links; }
db.Set(obj.cleanDevice(node));
// Event the node change
var event = { etype: 'node', userid: user._id, username: user.name, action: 'changenode', nodeid: node._id, domain: domain.id, msg: ('Removed user device rights for ' + node.name), node: obj.CloneSafeNode(node) }
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the mesh. Another event will come.
parent.DispatchEvent(['*', node.meshid, node._id], obj, event);
});
} else if (i.startsWith('ugrp/')) {
// Get the device group
var ugroup = obj.userGroups[i];
if (ugroup) {
// Remove user from the user group
if (ugroup.links[deluser._id] != null) { delete ugroup.links[deluser._id]; parent.db.Set(ugroup); }
// Notify user group change
var change = 'Removed user ' + deluser.name + ' from user group ' + ugroup.name;
var event = { etype: 'ugrp', userid: user._id, username: user.name, ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msg: 'Removed user ' + deluser.name + ' from user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user._id, deluser._id], obj, event);
}
}
}
}
// Remove notes for this user
obj.db.Remove('nt' + deluser._id);
// Remove the user
obj.db.Remove(deluser._id);
delete obj.users[deluser._id];
req.session = null;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
obj.parent.DispatchEvent(['*', 'server-users'], obj, { etype: 'user', userid: deluser._id, username: deluser.name, action: 'accountremove', msg: 'Account removed', domain: domain.id });
parent.debug('web', 'handleDeleteAccountRequest: removed user.');
} else {
parent.debug('web', 'handleDeleteAccountRequest: auth failed.');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
}
});
}
// Check a user's password
obj.checkUserPassword = function (domain, user, password, func) {
// Check the old password
if (user.passtype != null) {
// IIS default clear or weak password hashing (SHA-1)
require('./pass').iishash(user.passtype, password, user.salt, function (err, hash) {
if (err) { parent.debug('web', 'checkUserPassword: SHA-1 fail.'); return func(false); }
if (hash == user.hash) {
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { parent.debug('web', 'checkUserPassword: SHA-1 locked.'); return func(false); } // Account is locked
parent.debug('web', 'checkUserPassword: SHA-1 ok.');
return func(true); // Allow password change
}
func(false);
});
} else {
// Default strong password hashing (pbkdf2 SHA384)
require('./pass').hash(password, user.salt, function (err, hash, tag) {
if (err) { parent.debug('web', 'checkUserPassword: pbkdf2 SHA384 fail.'); return func(false); }
if (hash == user.hash) {
if ((user.siteadmin) && (user.siteadmin != 0xFFFFFFFF) && (user.siteadmin & 32) != 0) { parent.debug('web', 'checkUserPassword: pbkdf2 SHA384 locked.'); return func(false); } // Account is locked
parent.debug('web', 'checkUserPassword: pbkdf2 SHA384 ok.');
return func(true); // Allow password change
}
func(false);
}, 0);
}
}
// Check a user's old passwords
// Callback: 0=OK, 1=OldPass, 2=CommonPass
obj.checkOldUserPasswords = function (domain, user, password, func) {
// Check how many old passwords we need to check
if ((domain.passwordrequirements != null) && (typeof domain.passwordrequirements.oldpasswordban == 'number') && (domain.passwordrequirements.oldpasswordban > 0)) {
if (user.oldpasswords != null) {
const extraOldPasswords = user.oldpasswords.length - domain.passwordrequirements.oldpasswordban;
if (extraOldPasswords > 0) { user.oldpasswords.splice(0, extraOldPasswords); }
}
} else {
delete user.oldpasswords;
}
// If there is no old passwords, exit now.
var oldPassCount = 1;
if (user.oldpasswords != null) { oldPassCount += user.oldpasswords.length; }
var oldPassCheckState = { response: 0, count: oldPassCount, user: user, func: func };
// Test against common passwords if this feature is enabled
// Example of common passwords: 123456789, password123
if ((domain.passwordrequirements != null) && (domain.passwordrequirements.bancommonpasswords == true)) {
oldPassCheckState.count++;
require('wildleek')(password).then(function (wild) {
if (wild == true) { oldPassCheckState.response = 2; }
if (--oldPassCheckState.count == 0) { oldPassCheckState.func(oldPassCheckState.response); }
});
}
// Try current password
require('./pass').hash(password, user.salt, function oldPassCheck(err, hash, tag) {
if ((err == null) && (hash == tag.user.hash)) { tag.response = 1; }
if (--tag.count == 0) { tag.func(tag.response); }
}, oldPassCheckState);
// Try each old password
if (user.oldpasswords != null) {
for (var i in user.oldpasswords) {
const oldpassword = user.oldpasswords[i];
// Default strong password hashing (pbkdf2 SHA384)
require('./pass').hash(password, oldpassword.salt, function oldPassCheck(err, hash, tag) {
if ((err == null) && (hash == tag.oldPassword.hash)) { tag.state.response = 1; }
if (--tag.state.count == 0) { tag.state.func(tag.state.response); }
}, { oldPassword: oldpassword, state: oldPassCheckState });
}
}
}
// Handle password changes
function handlePasswordChangeRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { parent.debug('web', 'handlePasswordChangeRequest: failed checks (1).'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Check if the user is logged and we have all required parameters
if (!req.session || !req.session.userid || !req.body.apassword0 || !req.body.apassword1 || (req.body.apassword1 != req.body.apassword2) || (req.session.domainid != domain.id)) {
parent.debug('web', 'handlePasswordChangeRequest: failed checks (2).');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Get the current user
var user = obj.users[req.session.userid];
if (!user) {
parent.debug('web', 'handlePasswordChangeRequest: user not found.');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Check account settings locked
if ((user.siteadmin != 0xFFFFFFFF) && ((user.siteadmin & 1024) != 0)) {
parent.debug('web', 'handlePasswordChangeRequest: account settings locked.');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
return;
}
// Check old password
obj.checkUserPassword(domain, user, req.body.apassword1, function (result) {
if (result == true) {
// Check if the new password is allowed, only do this if this feature is enabled.
parent.checkOldUserPasswords(domain, user, command.newpass, function (result) {
if (result == 1) {
parent.debug('web', 'handlePasswordChangeRequest: old password reuse attempt.');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else if (result == 2) {
parent.debug('web', 'handlePasswordChangeRequest: commonly used password use attempt.');
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
} else {
// Update the password
require('./pass').hash(req.body.apassword1, function (err, salt, hash, tag) {
const nowSeconds = Math.floor(Date.now() / 1000);
if (err) { parent.debug('web', 'handlePasswordChangeRequest: hash error.'); throw err; }
if (domain.passwordrequirements != null) {
// Save password hint if this feature is enabled
if ((domain.passwordrequirements.hint === true) && (req.body.apasswordhint)) { var hint = req.body.apasswordhint; if (hint.length > 250) hint = hint.substring(0, 250); user.passhint = hint; } else { delete user.passhint; }
// Save previous password if this feature is enabled
if ((typeof domain.passwordrequirements.oldpasswordban == 'number') && (domain.passwordrequirements.oldpasswordban > 0)) {
if (user.oldpasswords == null) { user.oldpasswords = []; }
user.oldpasswords.push({ salt: user.salt, hash: user.hash, start: user.passchange, end: nowSeconds });
const extraOldPasswords = user.oldpasswords.length - domain.passwordrequirements.oldpasswordban;
if (extraOldPasswords > 0) { user.oldpasswords.splice(0, extraOldPasswords); }
}
}
user.salt = salt;
user.hash = hash;
user.passchange = nowSeconds;
delete user.passtype;
obj.db.SetUser(user);
req.session.viewmode = 2;
if (direct === true) { handleRootRequestEx(req, res, domain); } else { res.redirect(domain.url + getQueryPortion(req)); }
obj.parent.DispatchEvent(['*', 'server-users'], obj, { etype: 'user', userid: user._id, username: user.name, action: 'passchange', msg: 'Account password changed: ' + user.name, domain: domain.id });
}, 0);
}
});
}
});
}
// Called when a strategy login occured
// This is called after a succesful Oauth to Twitter, Google, GitHub...
function handleStrategyLogin(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
parent.debug('web', 'handleStrategyLogin: ' + JSON.stringify(req.user));
if ((req.user != null) && (req.user.sid != null)) {
const userid = 'user/' + domain.id + '/' + req.user.sid;
var user = obj.users[userid];
if (user == null) {
var newAccountAllowed = false;
var newAccountRealms = null;
if (domain.newaccounts === true) { newAccountAllowed = true; }
if (obj.common.validateStrArray(domain.newaccountrealms)) { newAccountRealms = domain.newaccountrealms; }
if ((domain.authstrategies != null) && (domain.authstrategies[req.user.strategy] != null)) {
if (domain.authstrategies[req.user.strategy].newaccounts === true) { newAccountAllowed = true; }
if (obj.common.validateStrArray(domain.authstrategies[req.user.strategy].newaccountrealms)) { newAccountRealms = domain.authstrategies[req.user.strategy].newaccountrealms; }
}
if (newAccountAllowed === true) {
// Create the user
parent.debug('web', 'handleStrategyLogin: creating new user: ' + userid);
user = { type: 'user', _id: userid, name: req.user.name, email: req.user.email, creation: Math.floor(Date.now() / 1000), domain: domain.id };
if (req.user.email != null) { user.email = req.user.email; user.emailVerified = true; }
if (domain.newaccountsrights) { user.siteadmin = domain.newaccountsrights; } // New accounts automatically assigned server rights.
if (domain.authstrategies[req.user.strategy].newaccountsrights) { user.siteadmin = obj.common.meshServerRightsArrayToNumber(domain.authstrategies[req.user.strategy].newaccountsrights); } // If there are specific SSO server rights, use these instead.
if (newAccountRealms) { user.groups = newAccountRealms; } // New accounts automatically part of some groups (Realms).
obj.users[userid] = user;
// Auto-join any user groups
var newaccountsusergroups = null;
if (typeof domain.newaccountsusergroups == 'object') { newaccountsusergroups = domain.newaccountsusergroups; }
if (typeof domain.authstrategies[req.user.strategy].newaccountsusergroups == 'object') { newaccountsusergroups = domain.authstrategies[req.user.strategy].newaccountsusergroups; }
if (newaccountsusergroups) {
for (var i in newaccountsusergroups) {
var ugrpid = newaccountsusergroups[i];
if (ugrpid.indexOf('/') < 0) { ugrpid = 'ugrp/' + domain.id + '/' + ugrpid; }
var ugroup = obj.userGroups[ugrpid];
if (ugroup != null) {
// Add group to the user
if (user.links == null) { user.links = {}; }
user.links[ugroup._id] = { rights: 1 };
// Add user to the group
ugroup.links[user._id] = { userid: user._id, name: user.name, rights: 1 };
db.Set(ugroup);
// Notify user group change
var event = { etype: 'ugrp', ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msg: 'Added user ' + user.name + ' to user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user._id], obj, event);
}
}
}
// Save the user
obj.db.SetUser(user);
// Event user creation
var targets = ['*', 'server-users'];
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountcreate', msg: 'Account created, username is ' + user.name, domain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
parent.DispatchEvent(targets, obj, event);
req.session.userid = userid;
req.session.domainid = domain.id;
} else {
// New users not allowed
parent.debug('web', 'handleStrategyLogin: Can\'t create new accounts');
req.session.loginmode = '1';
req.session.messageid = 100; // Unable to create account.
res.redirect(domain.url + getQueryPortion(req));
return;
}
} else {
// Login success
var userChange = false;
if ((req.user.name != null) && (req.user.name != user.name)) { user.name = req.user.name; userChange = true; }
if ((req.user.email != null) && (req.user.email != user.email)) { user.email = req.user.email; user.emailVerified = true; userChange = true; }
if (userChange) {
obj.db.SetUser(user);
// Event user creation
var targets = ['*', 'server-users'];
var event = { etype: 'user', userid: user._id, username: user.name, account: obj.CloneSafeUser(user), action: 'accountchange', msg: 'Account changed', domain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
parent.DispatchEvent(targets, obj, event);
}
parent.debug('web', 'handleStrategyLogin: succesful login: ' + userid);
req.session.userid = userid;
req.session.domainid = domain.id;
}
}
//res.redirect(domain.url); // This does not handle cookie correctly.
res.set('Content-Type', 'text/html');
res.end('<html><head><meta http-equiv="refresh" content=0;url="' + domain.url + '"></head><body></body></html>');
}
// Indicates that any request to "/" should render "default" or "login" depending on login state
function handleRootRequest(req, res, direct) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if (!obj.args) { parent.debug('web', 'handleRootRequest: no obj.args.'); res.sendStatus(500); return; }
if ((domain.sspi != null) && ((req.query.login == null) || (obj.parent.loginCookieEncryptionKey == null))) {
// Login using SSPI
domain.sspi.authenticate(req, res, function (err) {
if ((err != null) || (req.connection.user == null)) {
if (obj.parent.authlog) { obj.parent.authLog('https', 'Failed SSPI-auth for ' + req.connection.user + ' from ' + req.clientIp + ' port ' + req.connection.remotePort); }
parent.debug('web', 'handleRootRequest: SSPI auth required.');
res.end('Authentication Required...');
} else {
if (obj.parent.authlog) { obj.parent.authLog('https', 'Accepted SSPI-auth for ' + req.connection.user + ' from ' + req.clientIp + ' port ' + req.connection.remotePort); }
parent.debug('web', 'handleRootRequest: SSPI auth ok.');
handleRootRequestEx(req, res, domain, direct);
}
});
} else if (req.query.user && req.query.pass) {
// User credentials are being passed in the URL. WARNING: Putting credentials in a URL is bad security... but people are requesting this option.
obj.authenticate(req.query.user, req.query.pass, domain, function (err, userid) {
if (obj.parent.authlog) { obj.parent.authLog('https', 'Accepted password for ' + req.connection.user + ' from ' + req.clientIp + ' port ' + req.connection.remotePort); }
parent.debug('web', 'handleRootRequest: user/pass in URL auth ok.');
req.session.userid = userid;
req.session.domainid = domain.id;
req.session.currentNode = '';
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
handleRootRequestEx(req, res, domain, direct);
});
} else {
// Login using a different system
handleRootRequestEx(req, res, domain, direct);
}
}
function handleRootRequestEx(req, res, domain, direct) {
var nologout = false, user = null, features = 0;
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
// Check if we have an incomplete domain name in the path
if ((domain.id != '') && (domain.dns == null) && (req.url.split('/').length == 2)) {
parent.debug('web', 'handleRootRequestEx: incomplete domain name in the path.');
res.redirect(domain.url + getQueryPortion(req)); // BAD***
return;
}
if (obj.args.nousers == true) {
// If in single user mode, setup things here.
if (req.session && req.session.loginmode) { delete req.session.loginmode; }
req.session.userid = 'user/' + domain.id + '/~';
req.session.domainid = domain.id;
req.session.currentNode = '';
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
if (obj.users[req.session.userid] == null) {
// Create the dummy user ~ with impossible password
parent.debug('web', 'handleRootRequestEx: created dummy user in nouser mode.');
obj.users[req.session.userid] = { type: 'user', _id: req.session.userid, name: '~', email: '~', domain: domain.id, siteadmin: 4294967295 };
obj.db.SetUser(obj.users[req.session.userid]);
}
} else if (obj.args.user && obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]) {
// If a default user is active, setup the session here.
parent.debug('web', 'handleRootRequestEx: auth using default user.');
if (req.session && req.session.loginmode) { delete req.session.loginmode; }
req.session.userid = 'user/' + domain.id + '/' + obj.args.user.toLowerCase();
req.session.domainid = domain.id;
req.session.currentNode = '';
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
} else if (req.query.login && (obj.parent.loginCookieEncryptionKey != null)) {
var loginCookie = obj.parent.decodeCookie(req.query.login, obj.parent.loginCookieEncryptionKey, 60); // 60 minute timeout
//if ((loginCookie != null) && (obj.args.cookieipcheck !== false) && (loginCookie.ip != null) && (loginCookie.ip != req.clientIp)) { loginCookie = null; } // If the cookie if binded to an IP address, check here.
if ((loginCookie != null) && (loginCookie.a == 3) && (loginCookie.u != null) && (loginCookie.u.split('/')[1] == domain.id)) {
// If a login cookie was provided, setup the session here.
parent.debug('web', 'handleRootRequestEx: cookie auth ok.');
if (req.session && req.session.loginmode) { delete req.session.loginmode; }
req.session.userid = loginCookie.u;
req.session.domainid = domain.id;
req.session.currentNode = '';
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
} else {
parent.debug('web', 'handleRootRequestEx: cookie auth failed.');
}
} else if (domain.sspi != null) {
// SSPI login (Windows only)
//console.log(req.connection.user, req.connection.userSid);
if ((req.connection.user == null) || (req.connection.userSid == null)) {
parent.debug('web', 'handleRootRequestEx: SSPI no user auth.');
res.sendStatus(404); return;
} else {
nologout = true;
req.session.userid = 'user/' + domain.id + '/' + req.connection.user.toLowerCase();
req.session.usersid = req.connection.userSid;
req.session.usersGroups = req.connection.userGroups;
req.session.domainid = domain.id;
req.session.currentNode = '';
req.session.ip = req.clientIp; // Bind this session to the IP address of the request
// Check if this user exists, create it if not.
user = obj.users[req.session.userid];
if ((user == null) || (user.sid != req.session.usersid)) {
// Create the domain user
var usercount = 0, user2 = { type: 'user', _id: req.session.userid, name: req.connection.user, domain: domain.id, sid: req.session.usersid, creation: Math.floor(Date.now() / 1000), login: Math.floor(Date.now() / 1000) };
if (domain.newaccountsrights) { user2.siteadmin = domain.newaccountsrights; }
if (obj.common.validateStrArray(domain.newaccountrealms)) { user2.groups = domain.newaccountrealms; }
for (var i in obj.users) { if (obj.users[i].domain == domain.id) { usercount++; } }
if (usercount == 0) { user2.siteadmin = 4294967295; } // If this is the first user, give the account site admin.
// Auto-join any user groups
if (typeof domain.newaccountsusergroups == 'object') {
for (var i in domain.newaccountsusergroups) {
var ugrpid = domain.newaccountsusergroups[i];
if (ugrpid.indexOf('/') < 0) { ugrpid = 'ugrp/' + domain.id + '/' + ugrpid; }
var ugroup = obj.userGroups[ugrpid];
if (ugroup != null) {
// Add group to the user
if (user2.links == null) { user2.links = {}; }
user2.links[ugroup._id] = { rights: 1 };
// Add user to the group
ugroup.links[user2._id] = { userid: user2._id, name: user2.name, rights: 1 };
db.Set(ugroup);
// Notify user group change
var event = { etype: 'ugrp', ugrpid: ugroup._id, name: ugroup.name, desc: ugroup.desc, action: 'usergroupchange', links: ugroup.links, msg: 'Added user ' + user2.name + ' to user group ' + ugroup.name, addUserDomain: domain.id };
if (db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the user group. Another event will come.
parent.DispatchEvent(['*', ugroup._id, user2._id], obj, event);
}
}
}
obj.users[req.session.userid] = user2;
obj.db.SetUser(user2);
var event = { etype: 'user', userid: req.session.userid, username: req.connection.user, account: obj.CloneSafeUser(user2), action: 'accountcreate', msg: 'Domain account created, user ' + req.connection.user, domain: domain.id };
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to create the user. Another event will come.
obj.parent.DispatchEvent(['*', 'server-users'], obj, event);
parent.debug('web', 'handleRootRequestEx: SSPI new domain user.');
}
}
}
// Figure out the minimal password requirement
var passRequirements = null;
if (domain.passwordrequirements != null) {
if (domain.passrequirementstr == null) {
var passRequirements = {};
if (typeof domain.passwordrequirements.min == 'number') { passRequirements.min = domain.passwordrequirements.min; }
if (typeof domain.passwordrequirements.max == 'number') { passRequirements.max = domain.passwordrequirements.max; }
if (typeof domain.passwordrequirements.upper == 'number') { passRequirements.upper = domain.passwordrequirements.upper; }
if (typeof domain.passwordrequirements.lower == 'number') { passRequirements.lower = domain.passwordrequirements.lower; }
if (typeof domain.passwordrequirements.numeric == 'number') { passRequirements.numeric = domain.passwordrequirements.numeric; }
if (typeof domain.passwordrequirements.nonalpha == 'number') { passRequirements.nonalpha = domain.passwordrequirements.nonalpha; }
domain.passwordrequirementsstr = encodeURIComponent(JSON.stringify(passRequirements));
}
passRequirements = domain.passwordrequirementsstr;
}
// If a user exists and is logged in, serve the default app, otherwise server the login app.
if (req.session && req.session.userid && obj.users[req.session.userid]) {
var user = obj.users[req.session.userid];
if (req.session.domainid != domain.id) { // Check if the session is for the correct domain
parent.debug('web', 'handleRootRequestEx: incorrect domain.');
req.session = null;
res.redirect(domain.url + getQueryPortion(req)); // BAD***
return;
}
// Check if this is a locked account
if ((user.siteadmin != null) && ((user.siteadmin & 32) != 0) && (user.siteadmin != 0xFFFFFFFF)) {
// Locked account
parent.debug('web', 'handleRootRequestEx: locked account.');
delete req.session.userid;
delete req.session.domainid;
delete req.session.currentNode;
delete req.session.passhint;
delete req.session.cuserid;
req.session.messageid = 110; // Account locked.
res.redirect(domain.url + getQueryPortion(req)); // BAD***
return;
}
var viewmode = 1;
if (req.session.viewmode) {
viewmode = req.session.viewmode;
delete req.session.viewmode;
} else if (req.query.viewmode) {
viewmode = req.query.viewmode;
}
var currentNode = '';
if (req.session.currentNode) {
currentNode = req.session.currentNode;
delete req.session.currentNode;
} else if (req.query.node) {
currentNode = 'node/' + domain.id + '/' + req.query.node;
}
var logoutcontrols = {};
if (obj.args.nousers != true) { logoutcontrols.name = user.name; }
// Give the web page a list of supported server features
features = 0;
if (obj.args.wanonly == true) { features += 0x00000001; } // WAN-only mode
if (obj.args.lanonly == true) { features += 0x00000002; } // LAN-only mode
if (obj.args.nousers == true) { features += 0x00000004; } // Single user mode
if (domain.userQuota == -1) { features += 0x00000008; } // No server files mode
if (obj.args.mpstlsoffload) { features += 0x00000010; } // No mutual-auth CIRA
if ((parent.config.settings.allowframing != null) || (domain.allowframing != null)) { features += 0x00000020; } // Allow site within iframe
if ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true)) { features += 0x00000040; } // Email invites
if (obj.args.webrtc == true) { features += 0x00000080; } // Enable WebRTC (Default false for now)
if (obj.args.clickonce !== false) { features += 0x00000100; } // Enable ClickOnce (Default true)
if (obj.args.allowhighqualitydesktop !== false) { features += 0x00000200; } // Enable AllowHighQualityDesktop (Default true)
if (obj.args.lanonly == true || obj.args.mpsport == 0) { features += 0x00000400; } // No CIRA
if ((obj.parent.serverSelfWriteAllowed == true) && (user != null) && (user.siteadmin == 0xFFFFFFFF)) { features += 0x00000800; } // Server can self-write (Allows self-update)
if ((parent.config.settings.no2factorauth !== true) && (domain.auth != 'sspi') && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.nousers !== true) && (user._id.split('/')[2][0] != '~')) { features += 0x00001000; } // 2FA login supported
if (domain.agentnoproxy === true) { features += 0x00002000; } // Indicates that agents should be installed without using a HTTP proxy
if ((parent.config.settings.no2factorauth !== true) && domain.yubikey && domain.yubikey.id && domain.yubikey.secret && (user._id.split('/')[2][0] != '~')) { features += 0x00004000; } // Indicates Yubikey support
if (domain.geolocation == true) { features += 0x00008000; } // Enable geo-location features
if ((domain.passwordrequirements != null) && (domain.passwordrequirements.hint === true)) { features += 0x00010000; } // Enable password hints
if (parent.config.settings.no2factorauth !== true) { features += 0x00020000; } // Enable WebAuthn/FIDO2 support
if ((obj.args.nousers != true) && (domain.passwordrequirements != null) && (domain.passwordrequirements.force2factor === true) && (user._id.split('/')[2][0] != '~')) {
// Check if we can skip 2nd factor auth because of the source IP address
var skip2factor = false;
if ((req != null) && (req.clientIp != null) && (domain.passwordrequirements != null) && (domain.passwordrequirements.skip2factor != null)) {
for (var i in domain.passwordrequirements.skip2factor) {
if (require('ipcheck').match(req.clientIp, domain.passwordrequirements.skip2factor[i]) === true) { skip2factor = true; }
}
}
if (skip2factor == false) { features += 0x00040000; } // Force 2-factor auth
}
if ((domain.auth == 'sspi') || (domain.auth == 'ldap')) { features += 0x00080000; } // LDAP or SSPI in use, warn that users must login first before adding a user to a group.
if (domain.amtacmactivation) { features += 0x00100000; } // Intel AMT ACM activation/upgrade is possible
if (domain.usernameisemail) { features += 0x00200000; } // Username is email address
if (parent.mqttbroker != null) { features += 0x00400000; } // This server supports MQTT channels
if (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (parent.mailserver != null)) { features += 0x00800000; } // using email for 2FA is allowed
if (domain.agentinvitecodes == true) { features += 0x01000000; } // Support for agent invite codes
if (parent.smsserver != null) { features += 0x02000000; } // SMS messaging is supported
if ((parent.smsserver != null) && ((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false))) { features += 0x04000000; } // SMS 2FA is allowed
if (domain.sessionrecording != null) { features += 0x08000000; } // Server recordings enabled
if (domain.urlswitching === false) { features += 0x10000000; } // Disables the URL switching feature
if (domain.novnc === false) { features += 0x20000000; } // Disables noVNC
if (domain.mstsc !== true) { features += 0x40000000; } // Disables MSTSC.js
// Create a authentication cookie
const authCookie = obj.parent.encodeCookie({ userid: user._id, domainid: domain.id, ip: req.clientIp }, obj.parent.loginCookieEncryptionKey);
const authRelayCookie = obj.parent.encodeCookie({ ruserid: user._id, domainid: domain.id }, obj.parent.loginCookieEncryptionKey);
// Send the main web application
var extras = (req.query.key != null) ? ('&key=' + req.query.key) : '';
if ((!obj.args.user) && (obj.args.nousers != true) && (nologout == false)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
// Clean up the U2F challenge if needed
if (req.session.u2fchallenge) { delete req.session.u2fchallenge; };
// Intel AMT Scanning options
var amtscanoptions = '';
if (typeof domain.amtscanoptions == 'string') { amtscanoptions = encodeURIComponent(domain.amtscanoptions); }
else if (obj.common.validateStrArray(domain.amtscanoptions)) { domain.amtscanoptions = domain.amtscanoptions.join(','); amtscanoptions = encodeURIComponent(domain.amtscanoptions); }
// Fetch the web state
parent.debug('web', 'handleRootRequestEx: success.');
obj.db.Get('ws' + user._id, function (err, states) {
var webstate = (states.length == 1) ? obj.filterUserWebState(states[0].state) : '';
if ((webstate == '') && (typeof domain.defaultuserwebstate == 'object')) { webstate = JSON.stringify(domain.defaultuserwebstate); } // User has no web state, use defaults.
if (typeof domain.forceduserwebstate == 'object') { // Forces initial user web state is present, use it.
var webstate2 = {};
try { if (webstate != '') { webstate2 = JSON.parse(webstate); } } catch (ex) { }
for (var i in domain.forceduserwebstate) { webstate2[i] = domain.forceduserwebstate[i]; }
webstate = JSON.stringify(webstate2);
}
// Custom user interface
var customui = '';
if (domain.customui != null) { customui = encodeURIComponent(JSON.stringify(domain.customui)); }
// Refresh the session
render(req, res, getRenderPage('default', req, domain), getRenderArgs({ authCookie: authCookie, authRelayCookie: authRelayCookie, viewmode: viewmode, currentNode: currentNode, logoutControls: encodeURIComponent(JSON.stringify(logoutcontrols)).replace(/'/g, '%27'), domain: domain.id, debuglevel: parent.debugLevel, serverDnsName: obj.getWebServerName(domain), serverRedirPort: args.redirport, serverPublicPort: httpsPort, noServerBackup: (args.noserverbackup == 1 ? 1 : 0), features: features, sessiontime: args.sessiontime, mpspass: args.mpspass, passRequirements: passRequirements, customui: customui, webcerthash: Buffer.from(obj.webCertificateFullHashs[domain.id], 'binary').toString('base64').replace(/\+/g, '@').replace(/\//g, '$'), footer: (domain.footer == null) ? '' : domain.footer, webstate: encodeURIComponent(webstate).replace(/'/g, '%27'), amtscanoptions: amtscanoptions, pluginHandler: (parent.pluginHandler == null) ? 'null' : parent.pluginHandler.prepExports() }, req, domain));
});
} else {
// Send back the login application
// If this is a 2 factor auth request, look for a hardware key challenge.
// Normal login 2 factor request
if (req.session && (req.session.loginmode == '4') && (req.session.tokenuserid)) {
var user = obj.users[req.session.tokenuserid];
if (user != null) {
parent.debug('web', 'handleRootRequestEx: sending 2FA challenge.');
getHardwareKeyChallenge(req, domain, user, function (hwchallenge) { handleRootRequestLogin(req, res, domain, hwchallenge, passRequirements); });
return;
}
}
// Password recovery 2 factor request
if (req.session && (req.session.loginmode == '5') && (req.session.tokenemail)) {
obj.db.GetUserWithVerifiedEmail(domain.id, req.session.tokenemail, function (err, docs) {
if ((err != null) || (docs.length == 0)) {
parent.debug('web', 'handleRootRequestEx: password recover 2FA fail.');
req.session = null;
res.redirect(domain.url + getQueryPortion(req)); // BAD***
} else {
var user = obj.users[docs[0]._id];
if (user != null) {
parent.debug('web', 'handleRootRequestEx: password recover 2FA challenge.');
getHardwareKeyChallenge(req, domain, user, function (hwchallenge) { handleRootRequestLogin(req, res, domain, hwchallenge, passRequirements); });
} else {
parent.debug('web', 'handleRootRequestEx: password recover 2FA no user.');
req.session = null;
res.redirect(domain.url + getQueryPortion(req)); // BAD***
}
}
});
return;
}
handleRootRequestLogin(req, res, domain, '', passRequirements);
}
}
function handleRootRequestLogin(req, res, domain, hardwareKeyChallenge, passRequirements) {
parent.debug('web', 'handleRootRequestLogin()');
var features = 0;
if ((parent.config != null) && (parent.config.settings != null) && ((parent.config.settings.allowframing == true) || (typeof parent.config.settings.allowframing == 'string'))) { features += 32; } // Allow site within iframe
if (domain.usernameisemail) { features += 0x00200000; } // Username is email address
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
var loginmode = '';
if (req.session) { loginmode = req.session.loginmode; delete req.session.loginmode; } // Clear this state, if the user hits refresh, we want to go back to the login page.
// Format an error message if needed
var passhint = null, msgid = 0;
if (req.session != null) {
msgid = req.session.messageid;
if ((loginmode == '7') || ((domain.passwordrequirements != null) && (domain.passwordrequirements.hint === true))) { passhint = EscapeHtml(req.session.passhint); }
delete req.session.messageid;
delete req.session.passhint;
}
var emailcheck = ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true) && (domain.auth != 'sspi') && (domain.auth != 'ldap'))
// Check if we are allowed to create new users using the login screen
var newAccountsAllowed = true;
if ((domain.newaccounts !== 1) && (domain.newaccounts !== true)) { for (var i in obj.users) { if (obj.users[i].domain == domain.id) { newAccountsAllowed = false; break; } } }
// Encrypt the hardware key challenge state if needed
var hwstate = null;
if (hardwareKeyChallenge) { hwstate = obj.parent.encodeCookie({ u: req.session.tokenusername, p: req.session.tokenpassword, c: req.session.u2fchallenge }, obj.parent.loginCookieEncryptionKey) }
// Check if we can use OTP tokens with email
var otpemail = (parent.mailserver != null) && (req.session != null) && (req.session.tokenemail == true);
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.email2factor == false)) { otpemail = false; }
var otpsms = (parent.smsserver != null) && (req.session != null) && (req.session.tokensms == true);
if ((typeof domain.passwordrequirements == 'object') && (domain.passwordrequirements.sms2factor == false)) { otpsms = false; }
// See if we support two-factor trusted cookies
var twoFactorCookieDays = 30;
if (typeof domain.twofactorcookiedurationdays == 'number') { twoFactorCookieDays = domain.twofactorcookiedurationdays; }
// See what authentication strategies we have
var authStrategies = [];
if (typeof domain.authstrategies == 'object') {
if (typeof domain.authstrategies.twitter == 'object') { authStrategies.push('twitter'); }
if (typeof domain.authstrategies.google == 'object') { authStrategies.push('google'); }
if (typeof domain.authstrategies.github == 'object') { authStrategies.push('github'); }
if (typeof domain.authstrategies.reddit == 'object') { authStrategies.push('reddit'); }
if (typeof domain.authstrategies.azure == 'object') { authStrategies.push('azure'); }
if (typeof domain.authstrategies.intel == 'object') { authStrategies.push('intel'); }
if (typeof domain.authstrategies.jumpcloud == 'object') { authStrategies.push('jumpcloud'); }
if (typeof domain.authstrategies.saml == 'object') { authStrategies.push('saml'); }
}
// Custom user interface
var customui = '';
if (domain.customui != null) { customui = encodeURIComponent(JSON.stringify(domain.customui)); }
// Render the login page
render(req, res, getRenderPage('login', req, domain), getRenderArgs({ loginmode: loginmode, rootCertLink: getRootCertLink(), newAccount: newAccountsAllowed, newAccountPass: (((domain.newaccountspass == null) || (domain.newaccountspass == '')) ? 0 : 1), serverDnsName: obj.getWebServerName(domain), serverPublicPort: httpsPort, emailcheck: emailcheck, features: features, sessiontime: args.sessiontime, passRequirements: passRequirements, customui: customui, footer: (domain.footer == null) ? '' : domain.footer, hkey: encodeURIComponent(hardwareKeyChallenge).replace(/'/g, '%27'), messageid: msgid, passhint: passhint, welcometext: domain.welcometext ? encodeURIComponent(domain.welcometext).split('\'').join('\\\'') : null, hwstate: hwstate, otpemail: otpemail, otpsms: otpsms, twoFactorCookieDays: twoFactorCookieDays, authStrategies: authStrategies.join(',') }, req, domain));
}
// Handle a post request on the root
function handleRootPostRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.end("Not Found"); return; } // Check 3FA URL key
parent.debug('web', 'handleRootPostRequest, action: ' + req.body.action);
switch (req.body.action) {
case 'login': { handleLoginRequest(req, res, true); break; }
case 'tokenlogin': {
if (req.body.hwstate) {
var cookie = obj.parent.decodeCookie(req.body.hwstate, obj.parent.loginCookieEncryptionKey, 10);
if (cookie != null) { req.session.tokenusername = cookie.u; req.session.tokenpassword = cookie.p; req.session.u2fchallenge = cookie.c; }
}
handleLoginRequest(req, res, true); break;
}
case 'changepassword': { handlePasswordChangeRequest(req, res, true); break; }
case 'deleteaccount': { handleDeleteAccountRequest(req, res, true); break; }
case 'createaccount': { handleCreateAccountRequest(req, res, true); break; }
case 'resetpassword': { handleResetPasswordRequest(req, res, true); break; }
case 'resetaccount': { handleResetAccountRequest(req, res, true); break; }
case 'checkemail': { handleCheckAccountEmailRequest(req, res, true); break; }
default: { handleLoginRequest(req, res, true); break; }
}
}
// Return true if it looks like we are using a real TLS certificate.
obj.isTrustedCert = function (domain) {
if (obj.args.notls == true) return false; // We are not using TLS, so not trusted cert.
if ((domain != null) && (typeof domain.trustedcert == 'boolean')) return domain.trustedcert; // If the status of the cert specified, use that.
if (typeof obj.args.trustedcert == 'boolean') return obj.args.trustedcert; // If the status of the cert specified, use that.
if (obj.args.tlsoffload != null) return true; // We are using TLS offload, a real cert is likely used.
if (obj.parent.config.letsencrypt != null) return (obj.parent.config.letsencrypt.production === true); // We are using Let's Encrypt, real cert in use if production is set to true.
if (obj.certificates.WebIssuer.indexOf('MeshCentralRoot-') == 0) return false; // Our cert is issued by self-signed cert.
if (obj.certificates.CommonName.indexOf('.') == -1) return false; // Our cert is named with a fake name
return true; // This is a guess
}
// Get the link to the root certificate if needed
function getRootCertLink() {
// Check if the HTTPS certificate is issued from MeshCentralRoot, if so, add download link to root certificate.
if ((obj.args.notls == null) && (obj.args.tlsoffload == null) && (obj.parent.config.letsencrypt == null) && (obj.tlsSniCredentials == null) && (obj.certificates.WebIssuer.indexOf('MeshCentralRoot-') == 0) && (obj.certificates.CommonName.indexOf('.') != -1)) { return '<a href=/MeshServerRootCert.cer title="Download the root certificate for this server">Root Certificate</a>'; }
return '';
}
// Serve the xterm page
function handleXTermRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
parent.debug('web', 'handleXTermRequest: sending xterm');
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
if (req.session && req.session.userid) {
if (req.session.domainid != domain.id) { res.redirect(domain.url + getQueryPortion(req)); return; } // Check if the session is for the correct domain
var user = obj.users[req.session.userid];
if ((user == null) || (req.query.nodeid == null)) { res.redirect(domain.url + getQueryPortion(req)); return; } // Check if the user exists
// Check permissions
obj.GetNodeWithRights(domain, user, req.query.nodeid, function (node, rights, visible) {
if ((node == null) || ((rights & 8) == 0) || ((rights != 0xFFFFFFFF) && ((rights & 512) != 0))) { res.redirect(domain.url + getQueryPortion(req)); return; }
var logoutcontrols = { name: user.name };
var extras = (req.query.key != null) ? ('&key=' + req.query.key) : '';
if ((domain.ldap == null) && (domain.sspi == null) && (obj.args.user == null) && (obj.args.nousers != true)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
// Create a authentication cookie
const authCookie = obj.parent.encodeCookie({ userid: user._id, domainid: domain.id, ip: req.clientIp }, obj.parent.loginCookieEncryptionKey);
const authRelayCookie = obj.parent.encodeCookie({ ruserid: user._id, domainid: domain.id }, obj.parent.loginCookieEncryptionKey);
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
render(req, res, getRenderPage('xterm', req, domain), getRenderArgs({ serverDnsName: obj.getWebServerName(domain), serverRedirPort: args.redirport, serverPublicPort: httpsPort, authCookie: authCookie, authRelayCookie: authRelayCookie, logoutControls: encodeURIComponent(JSON.stringify(logoutcontrols)).replace(/'/g, '%27'), name: EscapeHtml(node.name) }, req, domain));
});
} else {
res.redirect(domain.url + getQueryPortion(req));
return;
}
}
// Render the terms of service.
function handleTermsRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// See if term.txt was loaded from the database
if ((parent.configurationFiles != null) && (parent.configurationFiles['terms.txt'] != null)) {
// Send the terms from the database
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
if (req.session && req.session.userid) {
if (req.session.domainid != domain.id) { req.session = null; res.redirect(domain.url + getQueryPortion(req)); return; } // Check if the session is for the correct domain
var user = obj.users[req.session.userid];
var logoutcontrols = { name: user.name };
var extras = (req.query.key != null) ? ('&key=' + req.query.key) : '';
if ((domain.ldap == null) && (domain.sspi == null) && (obj.args.user == null) && (obj.args.nousers != true)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
render(req, res, getRenderPage('terms', req, domain), getRenderArgs({ terms: encodeURIComponent(parent.configurationFiles['terms.txt'].toString()).split('\'').join('\\\''), logoutControls: encodeURIComponent(JSON.stringify(logoutcontrols)).replace(/'/g, '%27') }, req, domain));
} else {
render(req, res, getRenderPage('terms', req, domain), getRenderArgs({ terms: encodeURIComponent(parent.configurationFiles['terms.txt'].toString()).split('\'').join('\\\''), logoutControls: encodeURIComponent('{}') }, req, domain));
}
} else {
// See if there is a terms.txt file in meshcentral-data
var p = obj.path.join(obj.parent.datapath, 'terms.txt');
if (obj.fs.existsSync(p)) {
obj.fs.readFile(p, 'utf8', function (err, data) {
if (err != null) { parent.debug('web', 'handleTermsRequest: no terms.txt'); res.sendStatus(404); return; }
// Send the terms from terms.txt
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
if (req.session && req.session.userid) {
if (req.session.domainid != domain.id) { req.session = null; res.redirect(domain.url + getQueryPortion(req)); return; } // Check if the session is for the correct domain
var user = obj.users[req.session.userid];
var logoutcontrols = { name: user.name };
var extras = (req.query.key != null) ? ('&key=' + req.query.key) : '';
if ((domain.ldap == null) && (domain.sspi == null) && (obj.args.user == null) && (obj.args.nousers != true)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
render(req, res, getRenderPage('terms', req, domain), getRenderArgs({ terms: encodeURIComponent(data).split('\'').join('\\\''), logoutControls: encodeURIComponent(JSON.stringify(logoutcontrols)).replace(/'/g, '%27') }, req, domain));
} else {
render(req, res, getRenderPage('terms', req, domain), getRenderArgs({ terms: encodeURIComponent(data).split('\'').join('\\\''), logoutControls: encodeURIComponent('{}') }, req, domain));
}
});
} else {
// Send the default terms
parent.debug('web', 'handleTermsRequest: sending default terms');
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
if (req.session && req.session.userid) {
if (req.session.domainid != domain.id) { req.session = null; res.redirect(domain.url + getQueryPortion(req)); return; } // Check if the session is for the correct domain
var user = obj.users[req.session.userid];
var logoutcontrols = { name: user.name };
var extras = (req.query.key != null) ? ('&key=' + req.query.key) : '';
if ((domain.ldap == null) && (domain.sspi == null) && (obj.args.user == null) && (obj.args.nousers != true)) { logoutcontrols.logoutUrl = (domain.url + 'logout?' + Math.random() + extras); } // If a default user is in use or no user mode, don't display the logout button
render(req, res, getRenderPage('terms', req, domain), getRenderArgs({ logoutControls: encodeURIComponent(JSON.stringify(logoutcontrols)).replace(/'/g, '%27') }, req, domain));
} else {
render(req, res, getRenderPage('terms', req, domain), getRenderArgs({ logoutControls: encodeURIComponent('{}') }, req, domain));
}
}
}
}
// Render the messenger application.
function handleMessengerRequest(req, res) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'handleMessengerRequest: no domain'); res.sendStatus(404); return; }
parent.debug('web', 'handleMessengerRequest()');
var webRtcConfig = null;
if (obj.parent.config.settings && obj.parent.config.settings.webrtconfig && (typeof obj.parent.config.settings.webrtconfig == 'object')) { webRtcConfig = encodeURIComponent(JSON.stringify(obj.parent.config.settings.webrtconfig)).replace(/'/g, '%27'); }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
render(req, res, getRenderPage('messenger', req, domain), getRenderArgs({ webrtconfig: webRtcConfig }, req, domain));
}
// Returns the server root certificate encoded in base64
function getRootCertBase64() {
var rootcert = obj.certificates.root.cert;
var i = rootcert.indexOf('-----BEGIN CERTIFICATE-----\r\n');
if (i >= 0) { rootcert = rootcert.substring(i + 29); }
i = rootcert.indexOf('-----END CERTIFICATE-----');
if (i >= 0) { rootcert = rootcert.substring(i, 0); }
return Buffer.from(rootcert, 'base64').toString('base64');
}
// Returns the mesh server root certificate
function handleRootCertRequest(req, res) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'handleRootCertRequest: no domain'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((obj.userAllowedIp != null) && (checkIpAddressEx(req, res, obj.userAllowedIp, false) === false)) { parent.debug('web', 'handleRootCertRequest: invalid ip'); return; } // Check server-wide IP filter only.
parent.debug('web', 'handleRootCertRequest()');
try {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="' + certificates.RootName + '.cer"' });
} catch (ex) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="rootcert.cer"' });
}
res.send(Buffer.from(getRootCertBase64(), 'base64'));
}
// Return the CIRA configuration script
obj.getCiraCleanupScript = function (func) {
obj.fs.readFile(obj.parent.path.join(obj.parent.webPublicPath, 'scripts/cira_cleanup.mescript'), 'utf8', function (err, data) {
if (err != null) { func(null); return; }
func(Buffer.from(data));
});
}
// Return the CIRA configuration script
obj.getCiraConfigurationScript = function (meshid, func) {
var meshidx = meshid.split('/')[2].replace(/\@/g, 'X').replace(/\$/g, 'X').substring(0, 16);
var serverNameSplit = obj.certificates.AmtMpsName.split('.');
// Figure out the MPS port, use the alias if set
var mpsport = ((obj.args.mpsaliasport != null) ? obj.args.mpsaliasport : obj.args.mpsport);
if ((serverNameSplit.length == 4) && (parseInt(serverNameSplit[0]) == serverNameSplit[0]) && (parseInt(serverNameSplit[1]) == serverNameSplit[1]) && (parseInt(serverNameSplit[2]) == serverNameSplit[2]) && (parseInt(serverNameSplit[3]) == serverNameSplit[3])) {
// Server name is an IPv4 address
obj.fs.readFile(obj.parent.path.join(obj.parent.webPublicPath, 'scripts/cira_setup_script_ip.mescript'), 'utf8', function (err, data) {
if (err != null) { func(null); return; }
// Randomize the environement detection
var randomDnsName;
do { randomDnsName = getRandomLowerCase(14); } while (randomDnsName == 'aabbccddeeffgg');
while (data.indexOf('aabbccddeeffgg') >= 0) { data = data.replace('aabbccddeeffgg', randomDnsName); }
var scriptFile = JSON.parse(data);
// Change a few things in the script
scriptFile.scriptBlocks[2].vars.CertBin.value = getRootCertBase64(); // Set the root certificate
scriptFile.scriptBlocks[3].vars.IP.value = obj.certificates.AmtMpsName; // Set the server IPv4 address name
scriptFile.scriptBlocks[3].vars.ServerName.value = obj.certificates.AmtMpsName; // Set the server certificate name
scriptFile.scriptBlocks[3].vars.Port.value = mpsport; // Set the server MPS port
scriptFile.scriptBlocks[3].vars.username.value = meshidx; // Set the username
scriptFile.scriptBlocks[3].vars.password.value = obj.args.mpspass ? obj.args.mpspass : 'A@xew9rt'; // Set the password
scriptFile.scriptBlocks[4].vars.AccessInfo1.value = obj.certificates.AmtMpsName + ':' + mpsport; // Set the primary server name:port to set periodic timer
//scriptFile.scriptBlocks[4].vars.AccessInfo2.value = obj.certificates.AmtMpsName + ':' + mpsport; // Set the secondary server name:port to set periodic timer
if (obj.args.ciralocalfqdn != null) { scriptFile.scriptBlocks[6].vars.DetectionStrings.value = obj.args.ciralocalfqdn; } // Set the environment detection local FQDN's
// Compile the script
var scriptEngine = require('./amtscript.js').CreateAmtScriptEngine();
var runscript = scriptEngine.script_blocksToScript(scriptFile.blocks, scriptFile.scriptBlocks);
scriptFile.mescript = Buffer.from(scriptEngine.script_compile(runscript), 'binary').toString('base64');
scriptFile.scriptText = runscript;
// Send the script
func(Buffer.from(JSON.stringify(scriptFile, null, ' ')));
});
} else {
// Server name is a hostname
obj.fs.readFile(obj.parent.path.join(obj.parent.webPublicPath, 'scripts/cira_setup_script_dns.mescript'), 'utf8', function (err, data) {
if (err != null) { res.sendStatus(404); return; }
// Randomize the environement detection
var randomDnsName;
do { randomDnsName = getRandomLowerCase(14); } while (randomDnsName == 'aabbccddeeffgg');
while (data.indexOf('aabbccddeeffgg') >= 0) { data = data.replace('aabbccddeeffgg', randomDnsName); }
var scriptFile = JSON.parse(data);
// Change a few things in the script
scriptFile.scriptBlocks[2].vars.CertBin.value = getRootCertBase64(); // Set the root certificate
scriptFile.scriptBlocks[3].vars.FQDN.value = obj.certificates.AmtMpsName; // Set the server DNS name
scriptFile.scriptBlocks[3].vars.Port.value = mpsport; // Set the server MPS port
scriptFile.scriptBlocks[3].vars.username.value = meshidx; // Set the username
scriptFile.scriptBlocks[3].vars.password.value = obj.args.mpspass ? obj.args.mpspass : 'A@xew9rt'; // Set the password
scriptFile.scriptBlocks[4].vars.AccessInfo1.value = obj.certificates.AmtMpsName + ':' + mpsport; // Set the primary server name:port to set periodic timer
//scriptFile.scriptBlocks[4].vars.AccessInfo2.value = obj.certificates.AmtMpsName + ':' + mpsport; // Set the secondary server name:port to set periodic timer
if (obj.args.ciralocalfqdn != null) { scriptFile.scriptBlocks[6].vars.DetectionStrings.value = obj.args.ciralocalfqdn; } // Set the environment detection local FQDN's
// Compile the script
var scriptEngine = require('./amtscript.js').CreateAmtScriptEngine();
var runscript = scriptEngine.script_blocksToScript(scriptFile.blocks, scriptFile.scriptBlocks);
scriptFile.mescript = Buffer.from(scriptEngine.script_compile(runscript), 'binary').toString('base64');
scriptFile.scriptText = runscript;
// Send the script
func(Buffer.from(JSON.stringify(scriptFile, null, ' ')));
});
}
}
// Returns an mescript for Intel AMT configuration
function handleMeScriptRequest(req, res) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'handleMeScriptRequest: no domain'); res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((obj.userAllowedIp != null) && (checkIpAddressEx(req, res, obj.userAllowedIp, false) === false)) { return; } // Check server-wide IP filter only.
// Get the user and check user rights
var authUserid = null;
if ((req.session != null) && (typeof req.session.userid == 'string')) { authUserid = req.session.userid; }
if (authUserid == null) { res.sendStatus(401); return; }
const user = obj.users[authUserid];
if (user == null) { res.sendStatus(401); return; }
if ((req.query.type == 1) && (req.query.meshid != null)) {
// Get the CIRA install script
if (obj.IsMeshViewable(user, req.query.meshid) == false) { res.sendStatus(404); return; }
obj.getCiraConfigurationScript(req.query.meshid, function (script) {
if (script == null) { res.sendStatus(404); } else {
try {
var cirafilename = obj.meshes[req.query.meshid].name.split('\\').join('').split('/').join('').split(':').join('').split('*').join('').split('?').join('').split('"').join('').split('<').join('').split('>').join('').split('|').join('').split(' ').join('').split('\'').join('');
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="cira_setup_' + cirafilename + '.mescript"' });
} catch (ex) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="cira_setup.mescript"' });
}
res.send(script);
}
});
} else if (req.query.type == 2) {
// Get the CIRA cleanup script
obj.getCiraCleanupScript(function (script) {
if (script == null) { res.sendStatus(404); } else {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="cira_cleanup.mescript"' });
res.send(script);
}
});
} else {
res.sendStatus(404);
}
}
// Handle user public file downloads
function handleDownloadUserFiles(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if (obj.common.validateString(req.path, 1, 4096) == false) { res.sendStatus(404); return; }
var domainname = 'domain', spliturl = decodeURIComponent(req.path).split('/'), filename = '';
if ((spliturl.length < 3) || (obj.common.IsFilenameValid(spliturl[2]) == false) || (domain.userQuota == -1)) { res.sendStatus(404); return; }
if (domain.id != '') { domainname = 'domain-' + domain.id; }
var path = obj.path.join(obj.filespath, domainname + '/user-' + spliturl[2] + '/Public');
for (var i = 3; i < spliturl.length; i++) { if (obj.common.IsFilenameValid(spliturl[i]) == true) { path += '/' + spliturl[i]; filename = spliturl[i]; } else { res.sendStatus(404); return; } }
var stat = null;
try { stat = obj.fs.statSync(path); } catch (e) { }
if ((stat != null) && ((stat.mode & 0x004000) == 0)) {
if (req.query.download == 1) {
try {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=\"' + filename + '\"' });
} catch (ex) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=\"file.bin\"' });
}
try { res.sendFile(obj.path.resolve(__dirname, path)); } catch (e) { res.sendStatus(404); }
} else {
render(req, res, getRenderPage('download', req, domain), getRenderArgs({ rootCertLink: getRootCertLink(), message: "<a href='" + req.path + "?download=1'>" + filename + "</a>, " + stat.size + " byte" + ((stat.size < 2) ? '' : 's') + "." }, req, domain));
}
} else {
render(req, res, getRenderPage('download', req, domain), getRenderArgs({ rootCertLink: getRootCertLink(), message: "Invalid file link, please check the URL again." }, req, domain));
}
}
// Handle device file request
function handleDeviceFile(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((req.query.c == null) || (req.query.m == null) || (req.query.n == null) || (req.query.f == null)) { res.sendStatus(404); return; }
// Check the inbound desktop sharing cookie
var c = obj.parent.decodeCookie(req.query.c, obj.parent.loginCookieEncryptionKey, 60); // 60 minute timeout
if ((c == null) || (c.domainid !== domain.id)) { res.sendStatus(404); return; }
// Check userid
const user = obj.users[c.userid];
if ((c == user)) { res.sendStatus(404); return; }
// Check if this user has permission to manage this computer
const meshid = 'mesh/' + domain.id + '/' + req.query.m;
const nodeid = 'node/' + domain.id + '/' + req.query.n;
if ((obj.GetNodeRights(c.userid, meshid, nodeid) & MESHRIGHT_REMOTECONTROL) == 0) { res.sendStatus(404); return; }
// All good, start the file transfer
req.query.id = getRandomLowerCase(12);
obj.meshDeviceFileHandler.CreateMeshDeviceFile(obj, null, res, req, domain, user, meshid, nodeid);
}
// Handle logo request
function handleLogoRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
//res.set({ 'Cache-Control': 'max-age=86400' }); // 1 day
if (domain.titlepicture) {
if ((parent.configurationFiles != null) && (parent.configurationFiles[domain.titlepicture] != null)) {
// Use the logo in the database
res.set({ 'Content-Type': 'image/jpeg' });
res.send(parent.configurationFiles[domain.titlepicture]);
return;
} else {
// Use the logo on file
try { res.sendFile(obj.path.join(obj.parent.datapath, domain.titlepicture)); return; } catch (ex) { }
}
}
if ((domain.webpublicpath != null) && (obj.fs.existsSync(obj.path.join(domain.webpublicpath, 'images/logoback.png')))) {
// Use the domain logo picture
try { res.sendFile(obj.path.join(domain.webpublicpath, 'images/logoback.png')); } catch (ex) { res.sendStatus(404); }
} else if (parent.webPublicOverridePath && obj.fs.existsSync(obj.path.join(obj.parent.webPublicOverridePath, 'images/logoback.png'))) {
// Use the override logo picture
try { res.sendFile(obj.path.join(obj.parent.webPublicOverridePath, 'images/logoback.png')); } catch (ex) { res.sendStatus(404); }
} else {
// Use the default logo picture
try { res.sendFile(obj.path.join(obj.parent.webPublicPath, 'images/logoback.png')); } catch (ex) { res.sendStatus(404); }
}
}
// Handle translation request
function handleTranslationsRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
//if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((obj.userAllowedIp != null) && (checkIpAddressEx(req, res, obj.userAllowedIp, false) === false)) { return; } // Check server-wide IP filter only.
var user = null;
if (obj.args.user != null) {
// A default user is active
user = obj.users['user/' + domain.id + '/' + obj.args.user];
if (!user) { parent.debug('web', 'handleTranslationsRequest: user not found.'); res.sendStatus(401); return; }
} else {
// Check if the user is logged and we have all required parameters
if (!req.session || !req.session.userid) { parent.debug('web', 'handleTranslationsRequest: failed checks (2).'); res.sendStatus(401); return; }
// Get the current user
user = obj.users[req.session.userid];
if (!user) { parent.debug('web', 'handleTranslationsRequest: user not found.'); res.sendStatus(401); return; }
if (user.siteadmin != 0xFFFFFFFF) { parent.debug('web', 'handleTranslationsRequest: user not site administrator.'); res.sendStatus(401); return; }
}
var data = '';
req.setEncoding('utf8');
req.on('data', function (chunk) { data += chunk; });
req.on('end', function () {
try { data = JSON.parse(data); } catch (ex) { data = null; }
if (data == null) { res.sendStatus(404); return; }
if (data.action == 'getTranslations') {
if (obj.fs.existsSync(obj.path.join(obj.parent.datapath, 'translate.json'))) {
// Return the translation file (JSON)
try { res.sendFile(obj.path.join(obj.parent.datapath, 'translate.json')); } catch (ex) { res.sendStatus(404); }
} else if (obj.fs.existsSync(obj.path.join(__dirname, 'translate', 'translate.json'))) {
// Return the default translation file (JSON)
try { res.sendFile(obj.path.join(__dirname, 'translate', 'translate.json')); } catch (ex) { res.sendStatus(404); }
} else { res.sendStatus(404); }
} else if (data.action == 'setTranslations') {
obj.fs.writeFile(obj.path.join(obj.parent.datapath, 'translate.json'), obj.common.translationsToJson({ strings: data.strings }), function (err) { if (err == null) { res.send(JSON.stringify({ response: 'ok' })); } else { res.send(JSON.stringify({ response: err })); } });
} else if (data.action == 'translateServer') {
if (obj.pendingTranslation === true) { res.send(JSON.stringify({ response: 'Server is already performing a translation.' })); return; }
const nodeVersion = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
if (nodeVersion < 8) { res.send(JSON.stringify({ response: 'Server requires NodeJS 8.x or better.' })); return; }
var translateFile = obj.path.join(obj.parent.datapath, 'translate.json');
if (obj.fs.existsSync(translateFile) == false) { translateFile = obj.path.join(__dirname, 'translate', 'translate.json'); }
if (obj.fs.existsSync(translateFile) == false) { res.send(JSON.stringify({ response: 'Unable to find translate.js file on the server.' })); return; }
res.send(JSON.stringify({ response: 'ok' }));
console.log('Started server translation...');
obj.pendingTranslation = true;
require('child_process').exec('node translate.js translateall \"' + translateFile + '\"', { maxBuffer: 512000, timeout: 120000, cwd: obj.path.join(__dirname, 'translate') }, function (error, stdout, stderr) {
delete obj.pendingTranslation;
//console.log('error', error);
//console.log('stdout', stdout);
//console.log('stderr', stderr);
//console.log('Server restart...'); // Perform a server restart
//process.exit(0);
console.log('Server translation completed.');
});
} else {
// Unknown request
res.sendStatus(404);
}
});
}
// Handle welcome image request
function handleWelcomeImageRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
//res.set({ 'Cache-Control': 'max-age=86400' }); // 1 day
if (domain.welcomepicture) {
if ((parent.configurationFiles != null) && (parent.configurationFiles[domain.welcomepicture] != null)) {
// Use the welcome image in the database
res.set({ 'Content-Type': 'image/jpeg' });
res.send(parent.configurationFiles[domain.welcomepicture]);
return;
}
// Use the configured logo picture
try { res.sendFile(obj.path.join(obj.parent.datapath, domain.welcomepicture)); return; } catch (ex) { }
}
if (domain.webpublicpath != null) {
obj.fs.exists(obj.path.join(domain.webpublicpath, 'images/mainwelcome.jpg'), function (exists) {
if (exists) {
// Use the domain logo picture
try { res.sendFile(obj.path.join(domain.webpublicpath, 'images/mainwelcome.jpg')); } catch (ex) { res.sendStatus(404); }
} else {
// Use the default logo picture
try { res.sendFile(obj.path.join(obj.parent.webPublicPath, 'images/mainwelcome.jpg')); } catch (ex) { res.sendStatus(404); }
}
});
} else if (parent.webPublicOverridePath) {
obj.fs.exists(obj.path.join(obj.parent.webPublicOverridePath, 'images/mainwelcome.jpg'), function (exists) {
if (exists) {
// Use the override logo picture
try { res.sendFile(obj.path.join(obj.parent.webPublicOverridePath, 'images/mainwelcome.jpg')); } catch (ex) { res.sendStatus(404); }
} else {
// Use the default logo picture
try { res.sendFile(obj.path.join(obj.parent.webPublicPath, 'images/mainwelcome.jpg')); } catch (ex) { res.sendStatus(404); }
}
});
} else {
// Use the default logo picture
try { res.sendFile(obj.path.join(obj.parent.webPublicPath, 'images/mainwelcome.jpg')); } catch (ex) { res.sendStatus(404); }
}
}
// Download a desktop recording
function handleGetRecordings(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) return;
// Check the query
if ((domain.sessionrecording == null) || (req.query.file == null) || (obj.common.IsFilenameValid(req.query.file) !== true)) { res.sendStatus(401); return; }
// Get the recording path
var recordingsPath = null;
if (domain.sessionrecording.filepath) { recordingsPath = domain.sessionrecording.filepath; } else { recordingsPath = parent.recordpath; }
if (recordingsPath == null) { res.sendStatus(401); return; }
// Get the user and check user rights
var authUserid = null;
if ((req.session != null) && (typeof req.session.userid == 'string')) { authUserid = req.session.userid; }
if (authUserid == null) { res.sendStatus(401); return; }
const user = obj.users[authUserid];
if (user == null) { res.sendStatus(401); return; }
if ((user.siteadmin & 512) == 0) { res.sendStatus(401); return; } // Check if we have right to get recordings
// Send the recorded file
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=\"' + req.query.file + '\"' });
try { res.sendFile(obj.path.join(recordingsPath, req.query.file)); } catch (ex) { res.sendStatus(404); }
}
// Serve the player page
function handlePlayerRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
parent.debug('web', 'handlePlayerRequest: sending player');
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
render(req, res, getRenderPage('player', req, domain), getRenderArgs({}, req, domain));
}
// Serve the guest desktop page
function handleDesktopRequest(req, res) {
const domain = getDomain(req, res);
if (domain == null) { return; }
if (req.query.c == null) { res.sendStatus(404); return; }
// Check the inbound desktop sharing cookie
var c = obj.parent.decodeCookie(req.query.c, obj.parent.invitationLinkEncryptionKey, 60); // 60 minute timeout
if ((c == null) || (c.a !== 5) || (typeof c.uid != 'string') || (typeof c.nid != 'string') || (typeof c.gn != 'string') || (typeof c.cf != 'number') || (typeof c.expire != 'number') || (c.expire <= Date.now())) { res.sendStatus(404); return; }
// Looks good, let's create the outbound session cookies.
// Consent flags are 1 = Notify, 8 = Prompt, 64 = Privacy Bar.
const authCookie = obj.parent.encodeCookie({ userid: c.uid, domainid: domain.id, nid: c.nid, ip: req.clientIp, gn: c.gn, cf: 65 | c.cf, r: 8, expire: c.expire }, obj.parent.loginCookieEncryptionKey);
// Lets respond by sending out the desktop viewer.
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
parent.debug('web', 'handleDesktopRequest: Sending guest desktop page for \"' + c.uid + '\", guest \"' + c.gn + '\".');
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' });
render(req, res, getRenderPage('desktop', req, domain), getRenderArgs({ authCookie: authCookie, authRelayCookie: '', domainurl: encodeURIComponent(domain.url).replace(/'/g, '%27'), nodeid: c.nid, serverDnsName: obj.getWebServerName(domain), serverRedirPort: args.redirport, serverPublicPort: httpsPort, expire: c.expire }, req, domain));
}
// Handle domain redirection
obj.handleDomainRedirect = function (req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if (domain.redirects == null) { res.sendStatus(404); return; }
var urlArgs = '', urlName = null, splitUrl = req.originalUrl.split('?');
if (splitUrl.length > 1) { urlArgs = '?' + splitUrl[1]; }
if ((splitUrl.length > 0) && (splitUrl[0].length > 1)) { urlName = splitUrl[0].substring(1).toLowerCase(); }
if ((urlName == null) || (domain.redirects[urlName] == null) || (urlName[0] == '_')) { res.sendStatus(404); return; }
if (domain.redirects[urlName] == '~showversion') {
// Show the current version
res.end('MeshCentral v' + obj.parent.currentVer);
} else {
// Perform redirection
res.redirect(domain.redirects[urlName] + urlArgs + getQueryPortion(req));
}
}
// Take a "user/domain/userid/path/file" format and return the actual server disk file path if access is allowed
obj.getServerFilePath = function (user, domain, path) {
var splitpath = path.split('/'), serverpath = obj.path.join(obj.filespath, 'domain'), filename = '';
if ((splitpath.length < 3) || (splitpath[0] != 'user' && splitpath[0] != 'mesh') || (splitpath[1] != domain.id)) return null; // Basic validation
var objid = splitpath[0] + '/' + splitpath[1] + '/' + splitpath[2];
if (splitpath[0] == 'user' && (objid != user._id)) return null; // User validation, only self allowed
if (splitpath[0] == 'mesh') { if ((obj.GetMeshRights(user, objid) & 32) == 0) { return null; } } // Check mesh server file rights
if (splitpath[1] != '') { serverpath += '-' + splitpath[1]; } // Add the domain if needed
serverpath += ('/' + splitpath[0] + '-' + splitpath[2]);
for (var i = 3; i < splitpath.length; i++) { if (obj.common.IsFilenameValid(splitpath[i]) == true) { serverpath += '/' + splitpath[i]; filename = splitpath[i]; } else { return null; } } // Check that each folder is correct
return { fullpath: obj.path.resolve(obj.filespath, serverpath), path: serverpath, name: filename, quota: obj.getQuota(objid, domain) };
};
// Return the maximum number of bytes allowed in the user account "My Files".
obj.getQuota = function (objid, domain) {
if (objid == null) return 0;
if (objid.startsWith('user/')) {
var user = obj.users[objid];
if (user == null) return 0;
if (user.siteadmin == 0xFFFFFFFF) return null; // Administrators have no user limit
if ((user.quota != null) && (typeof user.quota == 'number')) { return user.quota; }
if ((domain != null) && (domain.userquota != null) && (typeof domain.userquota == 'number')) { return domain.userquota; }
return null; // By default, the user will have no limit
} else if (objid.startsWith('mesh/')) {
var mesh = obj.meshes[objid];
if (mesh == null) return 0;
if ((mesh.quota != null) && (typeof mesh.quota == 'number')) { return mesh.quota; }
if ((domain != null) && (domain.meshquota != null) && (typeof domain.meshquota == 'number')) { return domain.meshquota; }
return null; // By default, the mesh will have no limit
}
return 0;
};
// Download a file from the server
function handleDownloadFile(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((req.query.link == null) || (req.session == null) || (req.session.userid == null) || (domain == null) || (domain.userQuota == -1)) { res.sendStatus(404); return; }
const user = obj.users[req.session.userid];
if (user == null) { res.sendStatus(404); return; }
const file = obj.getServerFilePath(user, domain, req.query.link);
if (file == null) { res.sendStatus(404); return; }
try {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=\"' + file.name + '\"' });
} catch (ex) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename=\"file.bin\"' });
}
obj.fs.exists(file.fullpath, function (exists) { if (exists == true) { res.sendFile(file.fullpath); } else { res.sendStatus(404); } });
}
// Upload a MeshCore.js file to the server
function handleUploadMeshCoreFile(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if (domain.id !== '') { res.sendStatus(401); return; }
var authUserid = null;
if ((req.session != null) && (typeof req.session.userid == 'string')) { authUserid = req.session.userid; }
const multiparty = require('multiparty');
const form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
// If an authentication cookie is embedded in the form, use that.
if ((fields != null) && (fields.auth != null) && (fields.auth.length == 1) && (typeof fields.auth[0] == 'string')) {
var loginCookie = obj.parent.decodeCookie(fields.auth[0], obj.parent.loginCookieEncryptionKey, 60); // 60 minute timeout
if ((loginCookie != null) && (obj.args.cookieipcheck !== false) && (loginCookie.ip != null) && (loginCookie.ip != req.clientIp)) { loginCookie = null; } // Check cookie IP binding.
if ((loginCookie != null) && (domain.id == loginCookie.domainid)) { authUserid = loginCookie.userid; } // Use cookie authentication
}
if (authUserid == null) { res.sendStatus(401); return; }
// Get the user
const user = obj.users[authUserid];
if (user.siteadmin != 0xFFFFFFFF) { res.sendStatus(401); return; } // Check if we have mesh core upload rights (Full admin only)
if ((fields == null) || (fields.attrib == null) || (fields.attrib.length != 1)) { res.sendStatus(404); return; }
for (var i in files.files) {
var file = files.files[i];
obj.fs.readFile(file.path, 'utf8', function (err, data) {
if (err != null) return;
data = obj.common.IntToStr(0) + data; // Add the 4 bytes encoding type & flags (Set to 0 for raw)
obj.sendMeshAgentCore(user, domain, fields.attrib[0], 'custom', data); // Upload the core
try { obj.fs.unlinkSync(file.path); } catch (e) { }
});
}
res.send('');
});
}
// Upload a file to the server
function handleUploadFile(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if (domain.userQuota == -1) { res.sendStatus(401); return; }
var authUserid = null;
if ((req.session != null) && (typeof req.session.userid == 'string')) { authUserid = req.session.userid; }
const multiparty = require('multiparty');
const form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
// If an authentication cookie is embedded in the form, use that.
if ((fields != null) && (fields.auth != null) && (fields.auth.length == 1) && (typeof fields.auth[0] == 'string')) {
var loginCookie = obj.parent.decodeCookie(fields.auth[0], obj.parent.loginCookieEncryptionKey, 60); // 60 minute timeout
if ((loginCookie != null) && (obj.args.cookieipcheck !== false) && (loginCookie.ip != null) && (loginCookie.ip != req.clientIp)) { loginCookie = null; } // Check cookie IP binding.
if ((loginCookie != null) && (domain.id == loginCookie.domainid)) { authUserid = loginCookie.userid; } // Use cookie authentication
}
if (authUserid == null) { res.sendStatus(401); return; }
// Get the user
const user = obj.users[authUserid];
if ((user == null) || (user.siteadmin & 8) == 0) { res.sendStatus(401); return; } // Check if we have file rights
if ((fields == null) || (fields.link == null) || (fields.link.length != 1)) { /*console.log('UploadFile, Invalid Fields:', fields, files);*/ console.log('err4'); res.sendStatus(404); return; }
var xfile = null;
try { xfile = obj.getServerFilePath(user, domain, decodeURIComponent(fields.link[0])); } catch (ex) { }
if (xfile == null) { res.sendStatus(404); return; }
// Get total bytes in the path
var totalsize = readTotalFileSize(xfile.fullpath);
if ((xfile.quota == null) || (totalsize < xfile.quota)) { // Check if the quota is not already broken
if (fields.name != null) {
// See if we need to create the folder
var domainx = 'domain';
if (domain.id.length > 0) { domainx = 'domain-' + usersplit[1]; }
try { obj.fs.mkdirSync(obj.parent.filespath); } catch (ex) { }
try { obj.fs.mkdirSync(obj.parent.path.join(obj.parent.filespath, domainx)); } catch (ex) { }
try { obj.fs.mkdirSync(xfile.fullpath); } catch (ex) { }
// Upload method where all the file data is within the fields.
var names = fields.name[0].split('*'), sizes = fields.size[0].split('*'), types = fields.type[0].split('*'), datas = fields.data[0].split('*');
if ((names.length == sizes.length) && (types.length == datas.length) && (names.length == types.length)) {
for (var i = 0; i < names.length; i++) {
if (obj.common.IsFilenameValid(names[i]) == false) { res.sendStatus(404); return; }
var filedata = Buffer.from(datas[i].split(',')[1], 'base64');
if ((xfile.quota == null) || ((totalsize + filedata.length) < xfile.quota)) { // Check if quota would not be broken if we add this file
// Create the user folder if needed
(function (fullpath, filename, filedata) {
obj.fs.mkdir(xfile.fullpath, function () {
// Write the file
obj.fs.writeFile(obj.path.join(xfile.fullpath, filename), filedata, function () {
obj.parent.DispatchEvent([user._id], obj, 'updatefiles'); // Fire an event causing this user to update this files
});
});
})(xfile.fullpath, names[i], filedata);
} else {
// Send a notification
obj.parent.DispatchEvent([user._id], obj, { action: 'notify', title: "Disk quota exceed", value: names[i], nolog: 1, id: Math.random() });
}
}
}
} else {
// More typical upload method, the file data is in a multipart mime post.
for (var i in files.files) {
var file = files.files[i], fpath = obj.path.join(xfile.fullpath, file.originalFilename);
if (obj.common.IsFilenameValid(file.originalFilename) && ((xfile.quota == null) || ((totalsize + file.size) < xfile.quota))) { // Check if quota would not be broken if we add this file
// See if we need to create the folder
var domainx = 'domain';
if (domain.id.length > 0) { domainx = 'domain-' + domain.id; }
try { obj.fs.mkdirSync(obj.parent.filespath); } catch (e) { }
try { obj.fs.mkdirSync(obj.parent.path.join(obj.parent.filespath, domainx)); } catch (e) { }
try { obj.fs.mkdirSync(xfile.fullpath); } catch (e) { }
// Rename the file
obj.fs.rename(file.path, fpath, function (err) {
if (err && (err.code === 'EXDEV')) {
// On some Linux, the rename will fail with a "EXDEV" error, do a copy+unlink instead.
obj.common.copyFile(file.path, fpath, function (err) {
obj.fs.unlink(file.path, function (err) {
obj.parent.DispatchEvent([user._id], obj, 'updatefiles'); // Fire an event causing this user to update this files
});
});
} else {
obj.parent.DispatchEvent([user._id], obj, 'updatefiles'); // Fire an event causing this user to update this files
}
});
} else {
// Send a notification
obj.parent.DispatchEvent([user._id], obj, { action: 'notify', title: "Disk quota exceed", value: file.originalFilename, nolog: 1, id: Math.random() });
try { obj.fs.unlink(file.path, function (err) { }); } catch (e) { }
}
}
}
} else {
// Send a notification
obj.parent.DispatchEvent([user._id], obj, { action: 'notify', value: "Disk quota exceed", nolog: 1, id: Math.random() });
}
res.send('');
});
}
// Subscribe to all events we are allowed to receive
obj.subscribe = function (userid, target) {
const user = obj.users[userid];
const subscriptions = [userid, 'server-global'];
if (user.siteadmin != null) {
// Allow full site administrators of users with all events rights to see all events.
if ((user.siteadmin == 0xFFFFFFFF) || ((user.siteadmin & 2048) != 0)) { subscriptions.push('*'); }
else if ((user.siteadmin & 2) != 0) {
if ((user.groups == null) || (user.groups.length == 0)) {
// Subscribe to all user changes
subscriptions.push('server-users');
} else {
// Subscribe to user changes for some groups
for (var i in user.groups) { subscriptions.push('server-users:' + i); }
}
}
}
if (user.links != null) { for (var i in user.links) { subscriptions.push(i); } }
obj.parent.RemoveAllEventDispatch(target);
obj.parent.AddEventDispatch(subscriptions, target);
return subscriptions;
};
// Handle a web socket relay request
function handleRelayWebSocket(ws, req, domain, user, cookie) {
if (!(req.query.host)) { console.log('ERR: No host target specified'); try { ws.close(); } catch (e) { } return; } // Disconnect websocket
parent.debug('web', 'Websocket relay connected from ' + user.name + ' for ' + req.query.host + '.');
try { ws._socket.setKeepAlive(true, 240000); } catch (ex) { } // Set TCP keep alive
// Fetch information about the target
obj.db.Get(req.query.host, function (err, docs) {
if (docs.length == 0) { console.log('ERR: Node not found'); try { ws.close(); } catch (e) { } return; } // Disconnect websocket
var node = docs[0];
if (!node.intelamt) { console.log('ERR: Not AMT node'); try { ws.close(); } catch (e) { } return; } // Disconnect websocket
// Check if this user has permission to manage this computer
if ((obj.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0) { console.log('ERR: Access denied (3)'); try { ws.close(); } catch (e) { } return; }
// Check what connectivity is available for this node
var state = parent.GetConnectivityState(req.query.host);
var conn = 0;
if (!state || state.connectivity == 0) { parent.debug('web', 'ERR: No routing possible (1)'); try { ws.close(); } catch (e) { } return; } else { conn = state.connectivity; }
// Check what server needs to handle this connection
if ((obj.parent.multiServer != null) && ((cookie == null) || (cookie.ps != 1))) { // If a cookie is provided and is from a peer server, don't allow the connection to jump again to a different server
var server = obj.parent.GetRoutingServerId(req.query.host, 2); // Check for Intel CIRA connection
if (server != null) {
if (server.serverid != obj.parent.serverId) {
// Do local Intel CIRA routing using a different server
parent.debug('web', 'Route Intel AMT CIRA connection to peer server: ' + server.serverid);
obj.parent.multiServer.createPeerRelay(ws, req, server.serverid, user);
return;
}
} else {
server = obj.parent.GetRoutingServerId(req.query.host, 4); // Check for local Intel AMT connection
if ((server != null) && (server.serverid != obj.parent.serverId)) {
// Do local Intel AMT routing using a different server
parent.debug('web', 'Route Intel AMT direct connection to peer server: ' + server.serverid);
obj.parent.multiServer.createPeerRelay(ws, req, server.serverid, user);
return;
}
}
}
// Setup session recording if needed
if (domain.sessionrecording == true || ((typeof domain.sessionrecording == 'object') && ((domain.sessionrecording.protocols == null) || (domain.sessionrecording.protocols.indexOf((req.query.p == 2) ? 101 : 100) >= 0)))) { // TODO 100
var now = new Date(Date.now());
var recFilename = 'relaysession' + ((domain.id == '') ? '' : '-') + domain.id + '-' + now.getUTCFullYear() + '-' + obj.common.zeroPad(now.getUTCMonth(), 2) + '-' + obj.common.zeroPad(now.getUTCDate(), 2) + '-' + obj.common.zeroPad(now.getUTCHours(), 2) + '-' + obj.common.zeroPad(now.getUTCMinutes(), 2) + '-' + obj.common.zeroPad(now.getUTCSeconds(), 2) + '-' + getRandomPassword() + '.mcrec'
var recFullFilename = null;
if (domain.sessionrecording.filepath) {
try { obj.fs.mkdirSync(domain.sessionrecording.filepath); } catch (e) { }
recFullFilename = obj.path.join(domain.sessionrecording.filepath, recFilename);
} else {
try { obj.fs.mkdirSync(parent.recordpath); } catch (e) { }
recFullFilename = obj.path.join(parent.recordpath, recFilename);
}
var fd = obj.fs.openSync(recFullFilename, 'w');
if (fd != null) {
// Write the recording file header
var firstBlock = JSON.stringify({ magic: 'MeshCentralRelaySession', ver: 1, userid: user._id, username: user.name, ipaddr: req.clientIp, nodeid: node._id, intelamt: true, protocol: (req.query.p == 2) ? 101 : 100, time: new Date().toLocaleString() })
recordingEntry(fd, 1, 0, firstBlock, function () { });
ws.logfile = { fd: fd, lock: false };
if (req.query.p == 2) { ws.send(Buffer.from(String.fromCharCode(0xF0), 'binary')); } // Intel AMT Redirection: Indicate the session is being recorded
}
}
// If Intel AMT CIRA connection is available, use it
if (((conn & 2) != 0) && (parent.mpsserver.ciraConnections[req.query.host] != null)) {
parent.debug('web', 'Opening relay CIRA channel connection to ' + req.query.host + '.');
var ciraconn = parent.mpsserver.ciraConnections[req.query.host];
// Compute target port, look at the CIRA port mappings, if non-TLS is allowed, use that, if not use TLS
var port = 16993;
//if (node.intelamt.tls == 0) port = 16992; // DEBUG: Allow TLS flag to set TLS mode within CIRA
if (ciraconn.tag.boundPorts.indexOf(16992) >= 0) port = 16992; // RELEASE: Always use non-TLS mode if available within CIRA
if (req.query.p == 2) port += 2;
// Setup a new CIRA channel
if ((port == 16993) || (port == 16995)) {
// Perform TLS - ( TODO: THIS IS BROKEN on Intel AMT v7 but works on v10, Not sure why. Well, could be broken TLS 1.0 in firmware )
var ser = new SerialTunnel();
var chnl = parent.mpsserver.SetupCiraChannel(ciraconn, port);
// Let's chain up the TLSSocket <-> SerialTunnel <-> CIRA APF (chnl)
// Anything that needs to be forwarded by SerialTunnel will be encapsulated by chnl write
ser.forwardwrite = function (msg) {
// TLS ---> CIRA
chnl.write(msg.toString('binary'));
};
// When APF tunnel return something, update SerialTunnel buffer
chnl.onData = function (ciraconn, data) {
// CIRA ---> TLS
parent.debug('webrelay', 'Relay TLS CIRA data', data.length);
if (data.length > 0) { try { ser.updateBuffer(Buffer.from(data, 'binary')); } catch (ex) { console.log(ex); } }
};
// Handle CIRA tunnel state change
chnl.onStateChange = function (ciraconn, state) {
parent.debug('webrelay', 'Relay TLS CIRA state change', state);
if (state == 0) { try { ws.close(); } catch (e) { } }
};
// TLSSocket to encapsulate TLS communication, which then tunneled via SerialTunnel an then wrapped through CIRA APF
const TLSSocket = require('tls').TLSSocket;
const tlsoptions = { ciphers: 'RSA+AES:!aNULL:!MD5:!DSS', secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_COMPRESSION | constants.SSL_OP_CIPHER_SERVER_PREFERENCE, rejectUnauthorized: false };
if (req.query.tls1only == 1) { tlsoptions.secureProtocol = 'TLSv1_method'; }
const tlsock = new TLSSocket(ser, tlsoptions);
tlsock.on('error', function (err) { parent.debug('webrelay', "CIRA TLS Connection Error ", err); });
tlsock.on('secureConnect', function () { parent.debug('webrelay', "CIRA Secure TLS Connection"); ws._socket.resume(); });
// Decrypted tunnel from TLS communcation to be forwarded to websocket
tlsock.on('data', function (data) {
// AMT/TLS ---> WS
try {
data = data.toString('binary');
if (ws.interceptor) { data = ws.interceptor.processAmtData(data); } // Run data thru interceptor
//ws.send(Buffer.from(data, 'binary'));
ws.send(data);
} catch (e) { }
});
// If TLS is on, forward it through TLSSocket
ws.forwardclient = tlsock;
ws.forwardclient.xtls = 1;
} else {
// Without TLS
ws.forwardclient = parent.mpsserver.SetupCiraChannel(ciraconn, port);
ws.forwardclient.xtls = 0;
ws._socket.resume();
}
// When data is received from the web socket, forward the data into the associated CIRA cahnnel.
// If the CIRA connection is pending, the CIRA channel has built-in buffering, so we are ok sending anyway.
ws.on('message', function (msg) {
// WS ---> AMT/TLS
msg = msg.toString('binary');
if (ws.interceptor) { msg = ws.interceptor.processBrowserData(msg); } // Run data thru interceptor
//console.log('WS --> AMT', Buffer.from(msg, 'binary').toString('hex'));
// Log to recording file
if (ws.logfile == null) {
// Forward data to the associated TCP connection.
if (ws.forwardclient.xtls == 1) { ws.forwardclient.write(Buffer.from(msg, 'binary')); } else { ws.forwardclient.write(msg); }
} else {
// Log to recording file
var msg2 = Buffer.from(msg, 'binary');
recordingEntry(ws.logfile.fd, 2, 2, msg2, function () { try { if (ws.forwardclient.xtls == 1) { ws.forwardclient.write(msg2); } else { ws.forwardclient.write(msg); } } catch (ex) { } });
}
});
// If error, close the associated TCP connection.
ws.on('error', function (err) {
console.log('CIRA server websocket error from ' + req.clientIp + ', ' + err.toString().split('\r')[0] + '.');
parent.debug('webrelay', 'Websocket relay closed on error.');
if (ws.forwardclient && ws.forwardclient.close) { ws.forwardclient.close(); } // TODO: If TLS is used, we need to close the socket that is wrapped by TLS
// Close the recording file
if (ws.logfile != null) {
recordingEntry(ws.logfile.fd, 3, 0, 'MeshCentralMCREC', function (fd, ws) {
obj.fs.close(fd);
ws.logfile = null;
}, ws);
}
});
// If the web socket is closed, close the associated TCP connection.
ws.on('close', function (req) {
parent.debug('webrelay', 'Websocket relay closed.');
if (ws.forwardclient && ws.forwardclient.close) { ws.forwardclient.close(); } // TODO: If TLS is used, we need to close the socket that is wrapped by TLS
// Close the recording file
if (ws.logfile != null) {
recordingEntry(ws.logfile.fd, 3, 0, 'MeshCentralMCREC', function (fd, ws) {
obj.fs.close(fd);
ws.logfile = null;
}, ws);
}
});
ws.forwardclient.onStateChange = function (ciraconn, state) {
parent.debug('webrelay', 'Relay CIRA state change', state);
if (state == 0) { try { ws.close(); } catch (e) { } }
};
ws.forwardclient.onData = function (ciraconn, data) {
parent.debug('webrelaydata', 'Relay CIRA data', data.length);
if (ws.interceptor) { data = ws.interceptor.processAmtData(data); } // Run data thru interceptor
//console.log('AMT --> WS', Buffer.from(data, 'binary').toString('hex'));
if (data.length > 0) {
if (ws.logfile == null) {
try { ws.send(Buffer.from(data, 'binary')); } catch (e) { } // TODO: Add TLS support
} else {
// Log to recording file
data = Buffer.from(data, 'binary');
recordingEntry(ws.logfile.fd, 2, 0, data, function () { try { ws.send(data); } catch (ex) { console.log(ex); } }); // TODO: Add TLS support
}
}
};
ws.forwardclient.onSendOk = function (ciraconn) {
// TODO: Flow control? (Dont' really need it with AMT, but would be nice)
//console.log('onSendOk');
};
// Fetch Intel AMT credentials & Setup interceptor
if (req.query.p == 1) {
parent.debug('webrelaydata', 'INTERCEPTOR1', { host: node.host, port: port, user: node.intelamt.user, pass: node.intelamt.pass });
ws.interceptor = obj.interceptor.CreateHttpInterceptor({ host: node.host, port: port, user: node.intelamt.user, pass: node.intelamt.pass });
ws.interceptor.blockAmtStorage = true;
}
else if (req.query.p == 2) {
parent.debug('webrelaydata', 'INTERCEPTOR2', { user: node.intelamt.user, pass: node.intelamt.pass });
ws.interceptor = obj.interceptor.CreateRedirInterceptor({ user: node.intelamt.user, pass: node.intelamt.pass });
ws.interceptor.blockAmtStorage = true;
}
return;
}
// If Intel AMT direct connection is possible, option a direct socket
if ((conn & 4) != 0) { // We got a new web socket connection, initiate a TCP connection to the target Intel AMT host/port.
parent.debug('webrelay', 'Opening relay TCP socket connection to ' + req.query.host + '.');
// When data is received from the web socket, forward the data into the associated TCP connection.
ws.on('message', function (msg) {
if (obj.parent.debugLevel >= 1) { // DEBUG
parent.debug('webrelaydata', 'TCP relay data to ' + node.host + ', ' + msg.length + ' bytes');
//if (obj.parent.debugLevel >= 4) { parent.debug('webrelaydatahex', ' ' + msg.toString('hex')); }
}
msg = msg.toString('binary');
if (ws.interceptor) { msg = ws.interceptor.processBrowserData(msg); } // Run data thru interceptor
// Log to recording file
if (ws.logfile == null) {
// Forward data to the associated TCP connection.
try { ws.forwardclient.write(Buffer.from(msg, 'binary')); } catch (ex) { }
} else {
// Log to recording file
msg = Buffer.from(msg, 'binary');
recordingEntry(ws.logfile.fd, 2, 2, msg, function () { try { ws.forwardclient.write(msg); } catch (ex) { } });
}
});
// If error, close the associated TCP connection.
ws.on('error', function (err) {
console.log('Error with relay web socket connection from ' + req.clientIp + ', ' + err.toString().split('\r')[0] + '.');
parent.debug('webrelay', 'Error with relay web socket connection from ' + req.clientIp + '.');
if (ws.forwardclient) { try { ws.forwardclient.destroy(); } catch (e) { } }
// Close the recording file
if (ws.logfile != null) {
recordingEntry(ws.logfile.fd, 3, 0, 'MeshCentralMCREC', function (fd) {
obj.fs.close(fd);
ws.logfile = null;
});
}
});
// If the web socket is closed, close the associated TCP connection.
ws.on('close', function () {
parent.debug('webrelay', 'Closing relay web socket connection to ' + req.query.host + '.');
if (ws.forwardclient) { try { ws.forwardclient.destroy(); } catch (e) { } }
// Close the recording file
if (ws.logfile != null) {
recordingEntry(ws.logfile.fd, 3, 0, 'MeshCentralMCREC', function (fd) {
obj.fs.close(fd);
ws.logfile = null;
});
}
});
// Compute target port
var port = 16992;
if (node.intelamt.tls > 0) port = 16993; // This is a direct connection, use TLS when possible
if (req.query.p == 2) port += 2;
if (node.intelamt.tls == 0) {
// If this is TCP (without TLS) set a normal TCP socket
ws.forwardclient = new obj.net.Socket();
ws.forwardclient.setEncoding('binary');
ws.forwardclient.xstate = 0;
ws.forwardclient.forwardwsocket = ws;
ws._socket.resume();
} else {
// If TLS is going to be used, setup a TLS socket
var tlsoptions = { ciphers: 'RSA+AES:!aNULL:!MD5:!DSS', secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_COMPRESSION | constants.SSL_OP_CIPHER_SERVER_PREFERENCE, rejectUnauthorized: false };
if (req.query.tls1only == 1) { tlsoptions.secureProtocol = 'TLSv1_method'; }
ws.forwardclient = obj.tls.connect(port, node.host, tlsoptions, function () {
// The TLS connection method is the same as TCP, but located a bit differently.
parent.debug('webrelay', 'TLS connected to ' + node.host + ':' + port + '.');
ws.forwardclient.xstate = 1;
ws._socket.resume();
});
ws.forwardclient.setEncoding('binary');
ws.forwardclient.xstate = 0;
ws.forwardclient.forwardwsocket = ws;
}
// When we receive data on the TCP connection, forward it back into the web socket connection.
ws.forwardclient.on('data', function (data) {
if (obj.parent.debugLevel >= 1) { // DEBUG
parent.debug('webrelaydata', 'TCP relay data from ' + node.host + ', ' + data.length + ' bytes.');
//if (obj.parent.debugLevel >= 4) { Debug(4, ' ' + Buffer.from(data, 'binary').toString('hex')); }
}
if (ws.interceptor) { data = ws.interceptor.processAmtData(data); } // Run data thru interceptor
if (ws.logfile == null) {
// No logging
try { ws.send(Buffer.from(data, 'binary')); } catch (e) { }
} else {
// Log to recording file
data = Buffer.from(data, 'binary');
recordingEntry(ws.logfile.fd, 2, 0, data, function () { try { ws.send(data); } catch (e) { } });
}
});
// If the TCP connection closes, disconnect the associated web socket.
ws.forwardclient.on('close', function () {
parent.debug('webrelay', 'TCP relay disconnected from ' + node.host + ':' + port + '.');
try { ws.close(); } catch (e) { }
});
// If the TCP connection causes an error, disconnect the associated web socket.
ws.forwardclient.on('error', function (err) {
parent.debug('webrelay', 'TCP relay error from ' + node.host + ':' + port + ': ' + err);
try { ws.close(); } catch (e) { }
});
// Fetch Intel AMT credentials & Setup interceptor
if (req.query.p == 1) { ws.interceptor = obj.interceptor.CreateHttpInterceptor({ host: node.host, port: port, user: node.intelamt.user, pass: node.intelamt.pass }); }
else if (req.query.p == 2) { ws.interceptor = obj.interceptor.CreateRedirInterceptor({ user: node.intelamt.user, pass: node.intelamt.pass }); }
if (node.intelamt.tls == 0) {
// A TCP connection to Intel AMT just connected, start forwarding.
ws.forwardclient.connect(port, node.host, function () {
parent.debug('webrelay', 'TCP relay connected to ' + node.host + ':' + port + '.');
ws.forwardclient.xstate = 1;
ws._socket.resume();
});
}
return;
}
});
}
// Handle a Intel AMT activation request
function handleAmtActivateWebSocket(ws, req) {
const domain = checkUserIpAddress(ws, req);
if (domain == null) { return; }
if (req.query.id == null) { ws.send(JSON.stringify({ errorText: 'Missing group identifier' })); ws.close(); return; }
// Fetch the mesh object
ws.meshid = 'mesh/' + domain.id + '/' + req.query.id;
const mesh = obj.meshes[ws.meshid];
if (mesh == null) { ws.send(JSON.stringify({ errorText: 'Invalid device group: ' + ws.meshid })); delete ws.meshid; ws.close(); return; }
if (mesh.mtype != 1) { ws.send(JSON.stringify({ errorText: 'Invalid device group type:' + ws.meshid })); delete ws.meshid; ws.close(); return; }
// Fetch the remote IP:Port for logging
ws.remoteaddr = req.clientIp;
ws.remoteaddrport = ws.remoteaddr + ':' + ws._socket.remotePort;
// When data is received from the web socket, echo it back
ws.on('message', function (data) {
// Parse the incoming command
var cmd = null;
try { cmd = JSON.parse(data); } catch (ex) { };
if (cmd == null) return;
// Process the command
switch (cmd.action) {
case 'ccmactivate':
case 'acmactivate': {
// Check the command
if (cmd.version != 1) { ws.send(JSON.stringify({ errorText: 'Unsupported version' })); ws.close(); return; }
if (obj.common.validateString(cmd.realm, 16, 256) == false) { ws.send(JSON.stringify({ errorText: 'Invalid realm argument' })); ws.close(); return; }
if (obj.common.validateString(cmd.uuid, 36, 36) == false) { ws.send(JSON.stringify({ errorText: 'Invalid UUID argument' })); ws.close(); return; }
if (typeof cmd.hashes !== 'object') { ws.send(JSON.stringify({ errorText: 'Invalid hashes' })); ws.close(); return; }
if (typeof cmd.fqdn !== 'string') { ws.send(JSON.stringify({ errorText: 'Invalid FQDN' })); ws.close(); return; }
if ((obj.common.validateString(cmd.ver, 5, 16) == false) || (cmd.ver.split('.').length != 3)) { ws.send(JSON.stringify({ errorText: 'Invalid Intel AMT version' })); ws.close(); return; }
if (obj.common.validateArray(cmd.modes, 1, 2) == false) { ws.send(JSON.stringify({ errorText: 'Invalid activation modes' })); ws.close(); return; }
if (obj.common.validateInt(cmd.currentMode, 0, 2) == false) { ws.send(JSON.stringify({ errorText: 'Invalid current mode' })); ws.close(); return; }
if (typeof cmd.sku !== 'number') { ws.send(JSON.stringify({ errorText: 'Invalid SKU number' })); ws.close(); return; }
// Get the current Intel AMT policy
var mesh = obj.meshes[ws.meshid], activationMode = 4; // activationMode: 2 = CCM, 4 = ACM
if ((mesh == null) || (mesh.amt == null) || (mesh.amt.password == null) || ((mesh.amt.type != 2) && (mesh.amt.type != 3))) { ws.send(JSON.stringify({ errorText: 'Unable to activate' })); ws.close(); return; }
if ((mesh.amt.type != 3) || (domain.amtacmactivation == null) || (domain.amtacmactivation.acmmatch == null)) { activationMode = 2; }
if (activationMode == 4) {
// Check if we have a FQDN/Hash match
var matchingHash = null, matchingCN = null;
for (var i in domain.amtacmactivation.acmmatch) {
// Check for a matching FQDN
if ((domain.amtacmactivation.acmmatch[i].cn == '*') || (domain.amtacmactivation.acmmatch[i].cn.toLowerCase() == cmd.fqdn)) {
// Check for a matching certificate
if (cmd.hashes.indexOf(domain.amtacmactivation.acmmatch[i].sha256) >= 0) {
matchingCN = domain.amtacmactivation.acmmatch[i].cn;
matchingHash = domain.amtacmactivation.acmmatch[i].sha256;
continue;
} else if (cmd.hashes.indexOf(domain.amtacmactivation.acmmatch[i].sha1) >= 0) {
matchingCN = domain.amtacmactivation.acmmatch[i].cn;
matchingHash = domain.amtacmactivation.acmmatch[i].sha1;
continue;
}
}
}
// If no cert match or wildcard match which is not yet supported, do CCM activation.
if ((matchingHash == null) || (matchingCN == '*')) { ws.send(JSON.stringify({ messageText: 'No matching ACM activation certificates, activating in CCM instead...' })); activationMode = 2; } else { cmd.hash = matchingHash; }
}
// Check if we are going to activate in an allowed mode. cmd.modes: 1 = CCM, 2 = ACM
if ((activationMode == 4) && (cmd.modes.indexOf(2) == -1)) { ws.send(JSON.stringify({ messageText: 'ACM not allowed on this machine, activating in CCM instead...' })); activationMode = 2; } // We want to do ACM, but mode is not allowed. Change to CCM.
// If we want to do CCM, but mode is not allowed. Error out.
if ((activationMode == 2) && (cmd.modes.indexOf(1) == -1)) { ws.send(JSON.stringify({ errorText: 'CCM is not an allowed activation mode' })); ws.close(); return; }
// Get the Intel AMT admin password, randomize if needed.
var amtpassword = ((mesh.amt.password == '') ? getRandomAmtPassword() : mesh.amt.password);
if (checkAmtPassword(amtpassword) == false) { ws.send(JSON.stringify({ errorText: 'Invalid Intel AMT password' })); ws.close(); return; } // Invalid Intel AMT password, this should never happen.
// Save some state, if activation is successful, we need this to add the device
ws.xxstate = { uuid: cmd.uuid, realm: cmd.realm, tag: cmd.tag, name: cmd.name, hostname: cmd.hostname, pass: amtpassword, flags: activationMode, ver: cmd.ver, sku: cmd.sku }; // Flags: 2 = CCM, 4 = ACM
if (activationMode == 4) {
// ACM: Agent is asking the server to sign an Intel AMT ACM activation request
var signResponse = parent.certificateOperations.signAcmRequest(domain, cmd, 'admin', amtpassword, ws.remoteaddrport, null, ws.meshid, null, null);
ws.send(JSON.stringify(signResponse));
} else {
// CCM: Log the activation request, logging is a required step for activation.
if (parent.certificateOperations.logAmtActivation(domain, { time: new Date(), action: 'ccmactivate', domain: domain.id, amtUuid: cmd.uuid, amtRealm: cmd.realm, user: 'admin', password: amtpassword, ipport: ws.remoteaddrport, meshid: ws.meshid, tag: cmd.tag, name: cmd.name }) == false) return { errorText: 'Unable to log operation' };
// Compute the HTTP digest hash and send the response for CCM activation
ws.send(JSON.stringify({ action: 'ccmactivate', password: obj.crypto.createHash('md5').update('admin:' + cmd.realm + ':' + amtpassword).digest('hex') }));
}
break;
}
case 'ccmactivate-failed':
case 'acmactivate-failed': {
// Log the activation response
parent.certificateOperations.logAmtActivation(domain, { time: new Date(), action: cmd.action, domain: domain.id, amtUuid: cmd.uuid, ipport: ws.remoteaddrport, meshid: ws.meshid });
break;
}
case 'amtdiscover':
case 'ccmactivate-success':
case 'acmactivate-success': {
// If this is a discovery command, set the state.
if (cmd.action == 'amtdiscover') {
if (cmd.version != 1) { ws.send(JSON.stringify({ errorText: 'Unsupported version' })); ws.close(); return; }
if (obj.common.validateString(cmd.realm, 16, 256) == false) { ws.send(JSON.stringify({ errorText: 'Invalid realm argument' })); ws.close(); return; }
if (obj.common.validateString(cmd.uuid, 36, 36) == false) { ws.send(JSON.stringify({ errorText: 'Invalid UUID argument' })); ws.close(); return; }
if (typeof cmd.hashes != 'object') { ws.send(JSON.stringify({ errorText: 'Invalid hashes' })); ws.close(); return; }
if (typeof cmd.fqdn != 'string') { ws.send(JSON.stringify({ errorText: 'Invalid FQDN' })); ws.close(); return; }
if ((obj.common.validateString(cmd.ver, 5, 16) == false) || (cmd.ver.split('.').length != 3)) { ws.send(JSON.stringify({ errorText: 'Invalid Intel AMT version' })); ws.close(); return; }
if (obj.common.validateArray(cmd.modes, 1, 2) == false) { ws.send(JSON.stringify({ errorText: 'Invalid activation modes' })); ws.close(); return; }
if (obj.common.validateInt(cmd.currentMode, 0, 2) == false) { ws.send(JSON.stringify({ errorText: 'Invalid current mode' })); ws.close(); return; }
var activationMode = 0; if (cmd.currentMode == 1) { activationMode = 2; } else if (cmd.currentMode == 2) { activationMode = 4; }
ws.xxstate = { uuid: cmd.uuid, realm: cmd.realm, tag: cmd.tag, name: cmd.name, hostname: cmd.hostname, flags: activationMode, ver: cmd.ver, sku: cmd.sku }; // Flags: 2 = CCM, 4 = ACM
} else {
// If this is an activation success, check that state was set already.
if (ws.xxstate == null) { ws.send(JSON.stringify({ errorText: 'Invalid command' })); ws.close(); return; }
}
// Log the activation response
parent.certificateOperations.logAmtActivation(domain, { time: new Date(), action: cmd.action, domain: domain.id, amtUuid: cmd.uuid, ipport: ws.remoteaddrport, meshid: ws.meshid });
// Get the current Intel AMT policy
var mesh = obj.meshes[ws.meshid];
if (mesh == null) { ws.send(JSON.stringify({ errorText: 'Unknown device group' })); ws.close(); return; }
// Fix the computer name if needed
if ((ws.xxstate.name == null) || (ws.xxstate.name.length == 0)) { ws.xxstate.name = ws.xxstate.hostname; }
if ((ws.xxstate.name == null) || (ws.xxstate.name.length == 0)) { ws.xxstate.name = ws.xxstate.uuid; }
db.getAmtUuidNode(ws.meshid, ws.xxstate.uuid, function (err, nodes) {
if ((nodes == null) || (nodes.length == 0)) {
// Create a new nodeid
parent.crypto.randomBytes(48, function (err, buf) {
// Create the new node
var xxnodeid = 'node/' + domain.id + '/' + buf.toString('base64').replace(/\+/g, '@').replace(/\//g, '$');
var device = { type: 'node', _id: xxnodeid, meshid: ws.meshid, name: ws.xxstate.name, rname: ws.xxstate.name, host: ws.remoteaddr, domain: domain.id, intelamt: { state: 2, flags: ws.xxstate.flags, tls: 0, uuid: ws.xxstate.uuid, realm: ws.xxstate.realm, tag: ws.xxstate.tag, ver: ws.xxstate.ver, sku: ws.xxstate.sku } };
if (ws.xxstate.pass != null) { device.intelamt.user = 'admin'; device.intelamt.pass = ws.xxstate.pass; }
if (device.intelamt.flags != 0) { device.intelamt.state = 2; } else { device.intelamt.state = 0; }
db.Set(device);
// Event the new node
var device2 = Object.assign({}, device); // Shallow clone
device2.intelamt = Object.assign({}, device2.intelamt); // Shallow clone
delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
parent.DispatchEvent(['*', ws.meshid], obj, { etype: 'node', action: 'addnode', node: device2, msg: 'Added device ' + ws.xxstate.name + ' to mesh ' + mesh.name, domain: domain.id });
});
} else {
// Change an existing device
var device = nodes[0];
if (device.host != ws.remoteaddr) { device.host = ws.remoteaddr; }
if ((ws.xxstate.name != null) && (device.rname != ws.xxstate.name)) { device.rname = ws.xxstate.name; }
if (device.intelamt.flags != 0) {
if (device.intelamt.state != 2) { device.intelamt.state = 2; }
}
if (device.intelamt.flags != ws.xxstate.flags) { device.intelamt.state = ws.xxstate.flags; }
if (ws.xxstate.pass != null) {
if (device.intelamt.user != 'admin') { device.intelamt.user = 'admin'; }
if (device.intelamt.pass != ws.xxstate.pass) { device.intelamt.pass = ws.xxstate.pass; }
}
if (device.intelamt.realm != ws.xxstate.realm) { device.intelamt.realm = ws.xxstate.realm; }
if (ws.xxstate.realm == null) { delete device.intelamt.tag; }
else if (device.intelamt.tag != ws.xxstate.tag) { device.intelamt.tag = ws.xxstate.tag; }
if (device.intelamt.ver != ws.xxstate.ver) { device.intelamt.ver = ws.xxstate.ver; }
if (device.intelamt.sku != ws.xxstate.sku) { device.intelamt.sku = ws.xxstate.sku; }
db.Set(device);
// Event the new node
var device2 = Object.assign({}, device); // Shallow clone
device2.intelamt = Object.assign({}, device2.intelamt); // Shallow clone
delete device2.intelamt.pass; // Remove the Intel AMT password before eventing this.
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
parent.DispatchEvent(['*', ws.meshid], obj, { etype: 'node', action: 'changenode', nodeid: device2._id, node: device2, msg: 'Changed device ' + device.name + ' in mesh ' + mesh.name, domain: domain.id });
}
});
if (cmd.action == 'amtdiscover') { ws.send(JSON.stringify({ action: 'amtdiscover' })); }
break;
}
default: {
// This is not a known command
ws.send(JSON.stringify({ errorText: 'Invalid command' })); ws.close(); return;
}
}
});
// If close or error, do nothing.
ws.on('error', function (err) { });
ws.on('close', function (req) { });
}
// Setup agent to/from server file transfer handler
function handleAgentFileTransfer(ws, req) {
var domain = checkAgentIpAddress(ws, req);
if (domain == null) { parent.debug('web', 'Got agent file transfer connection with bad domain or blocked IP address ' + req.clientIp + ', dropping.'); ws.close(); return; }
if (req.query.c == null) { parent.debug('web', 'Got agent file transfer connection without a cookie from ' + req.clientIp + ', dropping.'); ws.close(); return; }
var c = obj.parent.decodeCookie(req.query.c, obj.parent.loginCookieEncryptionKey, 10); // 10 minute timeout
if ((c == null) || (c.a != 'aft')) { parent.debug('web', 'Got agent file transfer connection with invalid cookie from ' + req.clientIp + ', dropping.'); ws.close(); return; }
ws.xcmd = c.b; ws.xarg = c.c, ws.xfilelen = 0;
ws.send('c'); // Indicate connection of the tunnel. In this case, we are the termination point.
ws.send('5'); // Indicate we want to perform file transfers (5 = Files).
if (ws.xcmd == 'coredump') {
// Check the agent core dump folder if not already present.
var coreDumpPath = obj.path.join(parent.datapath, '..', 'meshcentral-coredumps');
if (obj.fs.existsSync(coreDumpPath) == false) { try { obj.fs.mkdirSync(coreDumpPath); } catch (ex) { } }
ws.xfilepath = obj.path.join(parent.datapath, '..', 'meshcentral-coredumps', ws.xarg);
ws.xid = 'coredump';
ws.send(JSON.stringify({ action: 'download', sub: 'start', ask: 'coredump', id: 'coredump' })); // Ask for a directory (test)
}
// When data is received from the web socket, echo it back
ws.on('message', function (data) {
if (typeof data == 'string') {
// Control message
var cmd = null;
try { cmd = JSON.parse(data); } catch (ex) { }
if ((cmd == null) || (cmd.action != 'download') || (cmd.sub == null)) return;
switch (cmd.sub) {
case 'start': {
// Perform an async file open
var callback = function onFileOpen(err, fd) {
onFileOpen.xws.xfile = fd;
onFileOpen.xws.send(JSON.stringify({ action: 'download', sub: 'startack', id: onFileOpen.xws.xid, ack: 1 })); // Ask for a directory (test)
};
callback.xws = this;
obj.fs.open(this.xfilepath, 'w', callback)
break;
}
}
} else {
// Binary message
if (data.length < 4) return;
var flags = data.readInt32BE(0);
if ((data.length > 4)) {
// Write the file
this.xfilelen += (data.length - 4);
try {
var callback = function onFileDataWritten(err, bytesWritten, buffer) {
if (onFileDataWritten.xflags & 1) {
// End of file
parent.debug('web', "Completed downloads of agent dumpfile, " + onFileDataWritten.xws.xfilelen + " bytes.");
if (onFileDataWritten.xws.xfile) { try { obj.fs.close(onFileDataWritten.xws.xfile, function (err) { }); } catch (ex) { } }
onFileDataWritten.xws.send(JSON.stringify({ action: 'markcoredump' })); // Ask to delete the core dump file
try { onFileDataWritten.xws.close(); } catch (ex) { }
} else {
// Send ack
onFileDataWritten.xws.send(JSON.stringify({ action: 'download', sub: 'ack', id: onFileDataWritten.xws.xid })); // Ask for a directory (test)
}
};
callback.xws = this;
callback.xflags = flags;
obj.fs.write(this.xfile, data, 4, data.length - 4, callback);
} catch (ex) { }
} else {
if (flags & 1) {
// End of file
parent.debug('web', "Completed downloads of agent dumpfile, " + this.xfilelen + " bytes.");
if (this.xfile) { try { obj.fs.close(this.xfile, function (err) { }); } catch (ex) { } }
this.send(JSON.stringify({ action: 'markcoredump' })); // Ask to delete the core dump file
try { this.close(); } catch (ex) { }
} else {
// Send ack
this.send(JSON.stringify({ action: 'download', sub: 'ack', id: this.xid })); // Ask for a directory (test)
}
}
}
});
// If error, do nothing.
ws.on('error', function (err) { console.log('Agent file transfer server error from ' + req.clientIp + ', ' + err.toString().split('\r')[0] + '.'); });
// If closed, do nothing
ws.on('close', function (req) { });
}
// Handle the web socket echo request, just echo back the data sent
function handleEchoWebSocket(ws, req) {
const domain = checkUserIpAddress(ws, req);
if (domain == null) { return; }
ws._socket.setKeepAlive(true, 240000); // Set TCP keep alive
// When data is received from the web socket, echo it back
ws.on('message', function (data) {
if (data.toString('utf8') == 'close') {
try { ws.close(); } catch (e) { console.log(e); }
} else {
try { ws.send(data); } catch (e) { console.log(e); }
}
});
// If error, do nothing.
ws.on('error', function (err) { console.log('Echo server error from ' + req.clientIp + ', ' + err.toString().split('\r')[0] + '.'); });
// If closed, do nothing
ws.on('close', function (req) { });
}
// Get the total size of all files in a folder and all sub-folders. (TODO: try to make all async version)
function readTotalFileSize(path) {
var r = 0, dir;
try { dir = obj.fs.readdirSync(path); } catch (e) { return 0; }
for (var i in dir) {
var stat = obj.fs.statSync(path + '/' + dir[i]);
if ((stat.mode & 0x004000) == 0) { r += stat.size; } else { r += readTotalFileSize(path + '/' + dir[i]); }
}
return r;
}
// Delete a folder and all sub items. (TODO: try to make all async version)
function deleteFolderRec(path) {
if (obj.fs.existsSync(path) == false) return;
try {
obj.fs.readdirSync(path).forEach(function (file, index) {
var pathx = path + '/' + file;
if (obj.fs.lstatSync(pathx).isDirectory()) { deleteFolderRec(pathx); } else { obj.fs.unlinkSync(pathx); }
});
obj.fs.rmdirSync(path);
} catch (ex) { }
}
// Handle Intel AMT events
// To subscribe, add "http://server:port/amtevents.ashx" to Intel AMT subscriptions.
obj.handleAmtEventRequest = function (req, res) {
const domain = getDomain(req);
try {
if (req.headers.authorization) {
var authstr = req.headers.authorization;
if (authstr.substring(0, 7) == 'Digest ') {
var auth = obj.common.parseNameValueList(obj.common.quoteSplit(authstr.substring(7)));
if ((req.url === auth.uri) && (obj.httpAuthRealm === auth.realm) && (auth.opaque === obj.crypto.createHmac('SHA384', obj.httpAuthRandom).update(auth.nonce).digest('hex'))) {
// Read the data, we need to get the arg field
var eventData = '';
req.on('data', function (chunk) { eventData += chunk; });
req.on('end', function () {
// Completed event read, let get the argument that must contain the nodeid
var i = eventData.indexOf('<m:arg xmlns:m="http://x.com">');
if (i > 0) {
var nodeid = eventData.substring(i + 30, i + 30 + 64);
if (nodeid.length == 64) {
var nodekey = 'node/' + domain.id + '/' + nodeid;
// See if this node exists in the database
obj.db.Get(nodekey, function (err, nodes) {
if (nodes.length == 1) {
// Yes, the node exists, compute Intel AMT digest password
var node = nodes[0];
var amtpass = obj.crypto.createHash('sha384').update(auth.username.toLowerCase() + ':' + nodeid + ":" + obj.parent.dbconfig.amtWsEventSecret).digest('base64').substring(0, 12).split('/').join('x').split('\\').join('x');
// Check the MD5 hash
if (auth.response === obj.common.ComputeDigesthash(auth.username, amtpass, auth.realm, 'POST', auth.uri, auth.qop, auth.nonce, auth.nc, auth.cnonce)) {
// This is an authenticated Intel AMT event, update the host address
var amthost = req.clientIp;
if (amthost.substring(0, 7) === '::ffff:') { amthost = amthost.substring(7); }
if (node.host != amthost) {
// Get the mesh for this device
var mesh = obj.meshes[node.meshid];
if (mesh) {
// Update the database
var oldname = node.host;
node.host = amthost;
obj.db.Set(obj.cleanDevice(node));
// Event the node change
var event = { etype: 'node', action: 'changenode', nodeid: node._id, domain: domain.id, msg: 'Intel(R) AMT host change ' + node.name + ' from group ' + mesh.name + ': ' + oldname + ' to ' + amthost };
// Remove the Intel AMT password before eventing this.
event.node = node;
if (event.node.intelamt && event.node.intelamt.pass) {
event.node = Object.assign({}, event.node); // Shallow clone
event.node.intelamt = Object.assign({}, event.node.intelamt); // Shallow clone
delete event.node.intelamt.pass;
}
if (obj.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
obj.parent.DispatchEvent(['*', node.meshid], obj, event);
}
}
parent.amtEventHandler.handleAmtEvent(eventData, nodeid, amthost);
//res.send('OK');
return;
}
}
});
}
}
});
}
}
}
} catch (e) { console.log(e); }
// Send authentication response
obj.crypto.randomBytes(48, function (err, buf) {
var nonce = buf.toString('hex'), opaque = obj.crypto.createHmac('SHA384', obj.httpAuthRandom).update(nonce).digest('hex');
res.set({ 'WWW-Authenticate': 'Digest realm="' + obj.httpAuthRealm + '", qop="auth,auth-int", nonce="' + nonce + '", opaque="' + opaque + '"' });
res.sendStatus(401);
});
};
// Handle a server backup request
function handleBackupRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((!req.session) || (req.session == null) || (!req.session.userid) || (obj.parent.args.noserverbackup == 1)) { res.sendStatus(401); return; }
var user = obj.users[req.session.userid];
if ((user == null) || ((user.siteadmin & 1) == 0)) { res.sendStatus(401); return; } // Check if we have server backup rights
// Require modules
const archive = require('archiver')('zip', { level: 9 }); // Sets the compression method to maximum.
// Good practice to catch this error explicitly
archive.on('error', function (err) { throw err; });
// Set the archive name
res.attachment((domain.title ? domain.title : 'MeshCentral') + '-Backup-' + new Date().toLocaleDateString().replace('/', '-').replace('/', '-') + '.zip');
// Pipe archive data to the file
archive.pipe(res);
// Append all of the files for this backup
var backupList = ['config.json', 'meshcentral.db', 'agentserver-cert-private.key', 'agentserver-cert-public.crt', 'mpsserver-cert-private.key', 'mpsserver-cert-public.crt', 'data/root-cert-private.key', 'root-cert-public.crt', 'webserver-cert-private.key', 'webserver-cert-public.crt'];
for (var i in backupList) {
var filename = backupList[i];
var filepath = obj.path.join(obj.parent.datapath, filename);
if (obj.fs.existsSync(filepath)) { archive.file(filepath, { name: filename }); }
}
// Finalize the archive (ie we are done appending files but streams have to finish yet)
archive.finalize();
}
// Handle a server restore request
function handleRestoreRequest(req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if (obj.parent.args.noserverbackup == 1) { res.sendStatus(401); return; }
var authUserid = null;
if ((req.session != null) && (typeof req.session.userid == 'string')) { authUserid = req.session.userid; }
const multiparty = require('multiparty');
const form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
// If an authentication cookie is embedded in the form, use that.
if ((fields != null) && (fields.auth != null) && (fields.auth.length == 1) && (typeof fields.auth[0] == 'string')) {
var loginCookie = obj.parent.decodeCookie(fields.auth[0], obj.parent.loginCookieEncryptionKey, 60); // 60 minute timeout
if ((loginCookie != null) && (obj.args.cookieipcheck !== false) && (loginCookie.ip != null) && (loginCookie.ip != req.clientIp)) { loginCookie = null; } // Check cookie IP binding.
if ((loginCookie != null) && (domain.id == loginCookie.domainid)) { authUserid = loginCookie.userid; } // Use cookie authentication
}
if (authUserid == null) { res.sendStatus(401); return; }
// Get the user
const user = obj.users[req.session.userid];
if ((user == null) || ((user.siteadmin & 4) == 0)) { res.sendStatus(401); return; } // Check if we have server restore rights
res.send('Server must be restarted, <a href="' + domain.url + '">click here to login</a>.');
parent.Stop(files.datafile[0].path);
});
}
// Handle a request to download a mesh agent
obj.handleMeshAgentRequest = function (req, res) {
var domain = getDomain(req, res);
if (domain == null) { parent.debug('web', 'handleRootRequest: invalid domain.'); try { res.sendStatus(404); } catch (ex) { } return; }
// If required, check if this user has rights to do this
if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true)) && (req.session.userid == null)) { res.sendStatus(401); return; }
if ((req.query.meshinstall != null) && (req.query.id != null)) {
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Send meshagent with included self installer for a specific platform back
// Start by getting the .msh for this request
var meshsettings = getMshFromRequest(req, res, domain);
if (meshsettings == null) { res.sendStatus(401); return; }
// Get the interactive install script, this only works for non-Windows agents
var agentid = parseInt(req.query.meshinstall);
var argentInfo = obj.parent.meshAgentBinaries[agentid];
var scriptInfo = obj.parent.meshAgentInstallScripts[6];
if ((argentInfo == null) || (scriptInfo == null) || (argentInfo.platform == 'win32')) { res.sendStatus(404); return; }
// Change the .msh file into JSON format and merge it into the install script
var tokens, msh = {}, meshsettingslines = meshsettings.split('\r').join('').split('\n');
for (var i in meshsettingslines) { tokens = meshsettingslines[i].split('='); if (tokens.length == 2) { msh[tokens[0]] = tokens[1]; } }
var js = scriptInfo.data.replace('var msh = {};', 'var msh = ' + JSON.stringify(msh) + ';');
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="meshagent"' });
res.statusCode = 200;
obj.parent.exeHandler.streamExeWithJavaScript({ platform: argentInfo.platform, sourceFileName: argentInfo.path, destinationStream: res, js: Buffer.from(js, 'utf8'), peinfo: argentInfo.pe });
} else if (req.query.id != null) {
// Send a specific mesh agent back
var argentInfo = obj.parent.meshAgentBinaries[req.query.id];
if (argentInfo == null) { res.sendStatus(404); return; }
if ((req.query.meshid == null) || (argentInfo.platform != 'win32')) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="' + argentInfo.rname + '"' });
if (argentInfo.data == null) { res.sendFile(argentInfo.path); } else { res.end(argentInfo.data); }
} else {
// Check if the meshid is a time limited, encrypted cookie
var meshcookie = obj.parent.decodeCookie(req.query.meshid, obj.parent.invitationLinkEncryptionKey);
if ((meshcookie != null) && (meshcookie.m != null)) { req.query.meshid = meshcookie.m; }
// We are going to embed the .msh file into the Windows executable (signed or not).
// First, fetch the mesh object to build the .msh file
var mesh = obj.meshes['mesh/' + domain.id + '/' + req.query.meshid];
if (mesh == null) { res.sendStatus(401); return; }
// If required, check if this user has rights to do this
if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true))) {
if ((domain.id != mesh.domain) || ((obj.GetMeshRights(req.session.userid, mesh) & 1) == 0)) { res.sendStatus(401); return; }
}
var meshidhex = Buffer.from(req.query.meshid.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
var serveridhex = Buffer.from(obj.agentCertificateHashBase64.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port if specified
if (obj.args.agentport != null) { httpsPort = obj.args.agentport; } // If an agent only port is enabled, use that.
if (obj.args.agentaliasport != null) { httpsPort = obj.args.agentaliasport; } // If an agent alias port is specified, use that.
// Prepare a mesh agent file name using the device group name.
var meshfilename = mesh.name
meshfilename = meshfilename.split('\\').join('').split('/').join('').split(':').join('').split('*').join('').split('?').join('').split('"').join('').split('<').join('').split('>').join('').split('|').join('').split(' ').join('').split('\'').join('');
if (argentInfo.rname.endsWith('.exe')) { meshfilename = argentInfo.rname.substring(0, argentInfo.rname.length - 4) + '-' + meshfilename + '.exe'; } else { meshfilename = argentInfo.rname + '-' + meshfilename; }
// Get the agent connection server name
var serverName = obj.getWebServerName(domain);
if (typeof obj.args.agentaliasdns == 'string') { serverName = obj.args.agentaliasdns; }
// Build the agent connection URL. If we are using a sub-domain or one with a DNS, we need to craft the URL correctly.
var xdomain = (domain.dns == null) ? domain.id : '';
if (xdomain != '') xdomain += '/';
var meshsettings = 'MeshName=' + mesh.name + '\r\nMeshType=' + mesh.mtype + '\r\nMeshID=0x' + meshidhex + '\r\nServerID=' + serveridhex + '\r\n';
if (obj.args.lanonly != true) { meshsettings += 'MeshServer=ws' + (obj.args.notls ? '' : 's') + '://' + serverName + ':' + httpsPort + '/' + xdomain + 'agent.ashx\r\n'; } else {
meshsettings += 'MeshServer=local\r\n';
if ((obj.args.localdiscovery != null) && (typeof obj.args.localdiscovery.key == 'string') && (obj.args.localdiscovery.key.length > 0)) { meshsettings += 'DiscoveryKey=' + obj.args.localdiscovery.key + '\r\n'; }
}
if ((req.query.tag != null) && (typeof req.query.tag == 'string') && (obj.common.isAlphaNumeric(req.query.tag) == true)) { meshsettings += 'Tag=' + req.query.tag + '\r\n'; }
if ((req.query.installflags != null) && (req.query.installflags != 0) && (parseInt(req.query.installflags) == req.query.installflags)) { meshsettings += 'InstallFlags=' + parseInt(req.query.installflags) + '\r\n'; }
if ((domain.agentnoproxy === true) || (obj.args.lanonly == true)) { meshsettings += 'ignoreProxyFile=1\r\n'; }
if (obj.args.agentconfig) { for (var i in obj.args.agentconfig) { meshsettings += obj.args.agentconfig[i] + '\r\n'; } }
if (domain.agentconfig) { for (var i in domain.agentconfig) { meshsettings += domain.agentconfig[i] + '\r\n'; } }
try {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="' + meshfilename + '"' });
} catch (ex) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="' + argentInfo.rname + '"' });
}
obj.parent.exeHandler.streamExeWithMeshPolicy({ platform: 'win32', sourceFileName: obj.parent.meshAgentBinaries[req.query.id].path, destinationStream: res, msh: meshsettings, peinfo: obj.parent.meshAgentBinaries[req.query.id].pe });
}
} else if (req.query.script != null) {
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Send a specific mesh install script back
var scriptInfo = obj.parent.meshAgentInstallScripts[req.query.script];
if (scriptInfo == null) { res.sendStatus(404); return; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename="' + scriptInfo.rname + '"' });
var data = scriptInfo.data;
var cmdoptions = { wgetoptionshttp: '', wgetoptionshttps: '', curloptionshttp: '-L ', curloptionshttps: '-L ' }
if (obj.isTrustedCert(domain) != true) {
cmdoptions.wgetoptionshttps += '--no-check-certificate ';
cmdoptions.curloptionshttps += '-k ';
}
if (domain.agentnoproxy === true) {
cmdoptions.wgetoptionshttp += '--no-proxy ';
cmdoptions.wgetoptionshttps += '--no-proxy ';
cmdoptions.curloptionshttp += '--noproxy \'*\' ';
cmdoptions.curloptionshttps += '--noproxy \'*\' ';
}
for (var i in cmdoptions) { data = data.split('{{{' + i + '}}}').join(cmdoptions[i]); }
res.send(data);
} else if (req.query.meshcmd != null) {
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
// Send meshcmd for a specific platform back
var agentid = parseInt(req.query.meshcmd);
// If the agentid is 3 or 4, check if we have a signed MeshCmd.exe
if ((agentid == 3)) { // Signed Windows MeshCmd.exe x86
var stats = null, meshCmdPath = obj.path.join(__dirname, 'agents', 'MeshCmd-signed.exe');
try { stats = obj.fs.statSync(meshCmdPath); } catch (e) { }
if ((stats != null)) { res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="meshcmd' + ((req.query.meshcmd <= 3) ? '.exe' : '') + '"' }); res.sendFile(meshCmdPath); return; }
} else if ((agentid == 4)) { // Signed Windows MeshCmd64.exe x64
var stats = null, meshCmd64Path = obj.path.join(__dirname, 'agents', 'MeshCmd64-signed.exe');
try { stats = obj.fs.statSync(meshCmd64Path); } catch (e) { }
if ((stats != null)) { res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="meshcmd' + ((req.query.meshcmd <= 4) ? '.exe' : '') + '"' }); res.sendFile(meshCmd64Path); return; }
}
// No signed agents, we are going to merge a new MeshCmd.
if ((agentid < 10000) && (obj.parent.meshAgentBinaries[agentid + 10000] != null)) { agentid += 10000; } // Avoid merging javascript to a signed mesh agent.
var argentInfo = obj.parent.meshAgentBinaries[agentid];
if ((argentInfo == null) || (obj.parent.defaultMeshCmd == null)) { res.sendStatus(404); return; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="meshcmd' + ((req.query.meshcmd <= 4) ? '.exe' : '') + '"' });
res.statusCode = 200;
if (argentInfo.signedMeshCmdPath != null) {
// If we have a pre-signed MeshCmd, send that.
res.sendFile(argentInfo.signedMeshCmdPath);
} else {
// Merge JavaScript to a unsigned agent and send that.
obj.parent.exeHandler.streamExeWithJavaScript({ platform: argentInfo.platform, sourceFileName: argentInfo.path, destinationStream: res, js: Buffer.from(obj.parent.defaultMeshCmd, 'utf8'), peinfo: argentInfo.pe });
}
} else if (req.query.meshaction != null) {
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
var user = obj.users[req.session.userid];
if (user == null) { res.sendStatus(404); return; }
if ((req.query.meshaction == 'route') && (req.query.nodeid != null)) {
obj.db.Get(req.query.nodeid, function (err, nodes) {
if (nodes.length != 1) { res.sendStatus(401); return; }
var node = nodes[0];
// Create the meshaction.txt file for meshcmd.exe
var meshaction = {
action: req.query.meshaction,
localPort: 1234,
remoteName: node.name,
remoteNodeId: node._id,
remoteTarget: null,
remotePort: 3389,
username: '',
password: '',
serverId: obj.agentCertificateHashHex.toUpperCase(), // SHA384 of server HTTPS public key
serverHttpsHash: Buffer.from(obj.webCertificateHashs[domain.id], 'binary').toString('hex').toUpperCase(), // SHA384 of server HTTPS certificate
debugLevel: 0
};
if (user != null) { meshaction.username = user.name; }
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
if (obj.args.lanonly != true) { meshaction.serverUrl = ((obj.args.notls == true) ? 'ws://' : 'wss://') + obj.getWebServerName(domain) + ':' + httpsPort + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename="meshaction.txt"' });
res.send(JSON.stringify(meshaction, null, ' '));
});
} else if (req.query.meshaction == 'generic') {
var meshaction = {
username: user.name,
password: '',
serverId: obj.agentCertificateHashHex.toUpperCase(), // SHA384 of server HTTPS public key
serverHttpsHash: Buffer.from(obj.webCertificateHashs[domain.id], 'binary').toString('hex').toUpperCase(), // SHA384 of server HTTPS certificate
debugLevel: 0
};
if (user != null) { meshaction.username = user.name; }
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
if (obj.args.lanonly != true) { meshaction.serverUrl = ((obj.args.notls == true) ? 'ws://' : 'wss://') + obj.getWebServerName(domain) + ':' + httpsPort + '/' + ((domain.id == '') ? '' : ('/' + domain.id)) + 'meshrelay.ashx'; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/plain', 'Content-Disposition': 'attachment; filename="meshaction.txt"' });
res.send(JSON.stringify(meshaction, null, ' '));
} else if (req.query.meshaction == 'winrouter') {
var p = obj.path.join(__dirname, 'agents', 'MeshCentralRouter.exe');
if (obj.fs.existsSync(p)) {
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="MeshCentralRouter.exe"' });
try { res.sendFile(p); } catch (e) { res.sendStatus(404); }
} else { res.sendStatus(404); }
} else {
res.sendStatus(401);
}
} else {
domain = checkUserIpAddress(req, res); // Recheck the domain to apply user IP filtering.
if (domain == null) return;
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((req.session == null) || (req.session.userid == null)) { res.sendStatus(404); return; }
// Send a list of available mesh agents
var response = '<html><head><title>Mesh Agents</title><style>table,th,td { border:1px solid black;border-collapse:collapse;padding:3px; }</style></head><body><table>';
response += '<tr style="background-color:lightgray"><th>ID</th><th>Description</th><th>Link</th><th>Size</th><th>SHA384</th><th>MeshCmd</th></tr>';
for (var agentid in obj.parent.meshAgentBinaries) {
var agentinfo = obj.parent.meshAgentBinaries[agentid];
var originalUrl = req.originalUrl.split('?')[0];
response += '<tr><td>' + agentinfo.id + '</td><td>' + agentinfo.desc + '</td>';
response += '<td><a download href="' + originalUrl + '?id=' + agentinfo.id + (req.query.key ? ('&key=' + req.query.key) : '') + '">' + agentinfo.rname + '</a></td>';
response += '<td>' + agentinfo.size + '</td><td>' + agentinfo.hashhex + '</td>';
response += '<td><a download href="' + originalUrl + '?meshcmd=' + agentinfo.id + (req.query.key ? ('&key=' + req.query.key) : '') + '">' + agentinfo.rname.replace('agent', 'cmd') + '</a></td></tr>';
}
response += '</table></body></html>';
res.send(response);
}
};
// Get the web server hostname. This may change if using a domain with a DNS name.
obj.getWebServerName = function (domain) {
if (domain.dns != null) return domain.dns;
return obj.certificates.CommonName;
}
// Create a OSX mesh agent installer
obj.handleMeshOsxAgentRequest = function (req, res) {
const domain = getDomain(req, res);
if (domain == null) { parent.debug('web', 'handleRootRequest: invalid domain.'); try { res.sendStatus(404); } catch (ex) { } return; }
if (req.query.id == null) { res.sendStatus(404); return; }
// If required, check if this user has rights to do this
if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true)) && (req.session.userid == null)) { res.sendStatus(401); return; }
// Send a specific mesh agent back
var argentInfo = obj.parent.meshAgentBinaries[req.query.id];
if ((argentInfo == null) || (req.query.meshid == null)) { res.sendStatus(404); return; }
// Check if the meshid is a time limited, encrypted cookie
var meshcookie = obj.parent.decodeCookie(req.query.meshid, obj.parent.invitationLinkEncryptionKey);
if ((meshcookie != null) && (meshcookie.m != null)) { req.query.meshid = meshcookie.m; }
// We are going to embed the .msh file into the Windows executable (signed or not).
// First, fetch the mesh object to build the .msh file
var mesh = obj.meshes['mesh/' + domain.id + '/' + req.query.meshid];
if (mesh == null) { res.sendStatus(401); return; }
// If required, check if this user has rights to do this
if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true))) {
if ((domain.id != mesh.domain) || ((obj.GetMeshRights(req.session.userid, mesh) & 1) == 0)) { res.sendStatus(401); return; }
}
var meshidhex = Buffer.from(req.query.meshid.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
var serveridhex = Buffer.from(obj.agentCertificateHashBase64.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
// Get the agent connection server name
var serverName = obj.getWebServerName(domain);
if (typeof obj.args.agentaliasdns == 'string') { serverName = obj.args.agentaliasdns; }
// Build the agent connection URL. If we are using a sub-domain or one with a DNS, we need to craft the URL correctly.
var xdomain = (domain.dns == null) ? domain.id : '';
if (xdomain != '') xdomain += '/';
var meshsettings = 'MeshName=' + mesh.name + '\r\nMeshType=' + mesh.mtype + '\r\nMeshID=0x' + meshidhex + '\r\nServerID=' + serveridhex + '\r\n';
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
if (obj.args.agentport != null) { httpsPort = obj.args.agentport; } // If an agent only port is enabled, use that.
if (obj.args.agentaliasport != null) { httpsPort = obj.args.agentaliasport; } // If an agent alias port is specified, use that.
if (obj.args.lanonly != true) { meshsettings += 'MeshServer=ws' + (obj.args.notls ? '' : 's') + '://' + serverName + ':' + httpsPort + '/' + xdomain + 'agent.ashx\r\n'; } else {
meshsettings += 'MeshServer=local\r\n';
if ((obj.args.localdiscovery != null) && (typeof obj.args.localdiscovery.key == 'string') && (obj.args.localdiscovery.key.length > 0)) { meshsettings += 'DiscoveryKey=' + obj.args.localdiscovery.key + '\r\n'; }
}
if ((req.query.tag != null) && (typeof req.query.tag == 'string') && (obj.common.isAlphaNumeric(req.query.tag) == true)) { meshsettings += 'Tag=' + req.query.tag + '\r\n'; }
if ((req.query.installflags != null) && (req.query.installflags != 0) && (parseInt(req.query.installflags) == req.query.installflags)) { meshsettings += 'InstallFlags=' + parseInt(req.query.installflags) + '\r\n'; }
if ((domain.agentnoproxy === true) || (obj.args.lanonly == true)) { meshsettings += 'ignoreProxyFile=1\r\n'; }
if (obj.args.agentconfig) { for (var i in obj.args.agentconfig) { meshsettings += obj.args.agentconfig[i] + '\r\n'; } }
if (domain.agentconfig) { for (var i in domain.agentconfig) { meshsettings += domain.agentconfig[i] + '\r\n'; } }
// Setup the response output
var archive = require('archiver')('zip', { level: 5 }); // Sets the compression method.
archive.on('error', function (err) { throw err; });
try {
// Set the agent download including the mesh name.
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename="MeshAgent-' + mesh.name + '.zip"' });
} catch (ex) {
// If the mesh name contains invalid characters, just use a generic name.
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/zip', 'Content-Disposition': 'attachment; filename="MeshAgent.zip"' });
}
archive.pipe(res);
// Opens the "MeshAgentOSXPackager.zip"
var yauzl = require('yauzl');
yauzl.open(obj.path.join(__dirname, 'agents', 'MeshAgentOSXPackager.zip'), { lazyEntries: true }, function (err, zipfile) {
if (err) { res.sendStatus(500); return; }
zipfile.readEntry();
zipfile.on('entry', function (entry) {
if (/\/$/.test(entry.fileName)) {
// Skip all folder entries
zipfile.readEntry();
} else {
if (entry.fileName == 'MeshAgent.mpkg/Contents/distribution.dist') {
// This is a special file entry, we need to fix it.
zipfile.openReadStream(entry, function (err, readStream) {
readStream.on('data', function (data) { if (readStream.xxdata) { readStream.xxdata += data; } else { readStream.xxdata = data; } });
readStream.on('end', function () {
var meshname = mesh.name.split(']').join('').split('[').join(''); // We can't have ']]' in the string since it will terminate the CDATA.
var welcomemsg = 'Welcome to the MeshCentral agent for MacOS\n\nThis installer will install the mesh agent for "' + meshname + '" and allow the administrator to remotely monitor and control this computer over the internet. For more information, go to https://www.meshcommander.com/meshcentral2.\n\nThis software is provided under Apache 2.0 license.\n';
var installsize = Math.floor((argentInfo.size + meshsettings.length) / 1024);
archive.append(readStream.xxdata.toString().split('###WELCOMEMSG###').join(welcomemsg).split('###INSTALLSIZE###').join(installsize), { name: entry.fileName });
zipfile.readEntry();
});
});
} else {
// Normal file entry
zipfile.openReadStream(entry, function (err, readStream) {
if (err) { throw err; }
var options = { name: entry.fileName };
if (entry.fileName.endsWith('postflight') || entry.fileName.endsWith('Uninstall.command')) { options.mode = 493; }
archive.append(readStream, options);
readStream.on('end', function () { zipfile.readEntry(); });
});
}
}
});
zipfile.on('end', function () {
archive.file(argentInfo.path, { name: 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/meshagent_osx64.bin' });
archive.append(meshsettings, { name: 'MeshAgent.mpkg/Contents/Packages/internal.pkg/Contents/meshagent_osx64.msh' });
archive.finalize();
});
});
}
// Return a .msh file from a given request, id is the device group identifier or encrypted cookie with the identifier.
function getMshFromRequest(req, res, domain) {
// If required, check if this user has rights to do this
if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true)) && (req.session.userid == null)) { return null; }
// Check if the meshid is a time limited, encrypted cookie
var meshcookie = obj.parent.decodeCookie(req.query.id, obj.parent.invitationLinkEncryptionKey);
if ((meshcookie != null) && (meshcookie.m != null)) { req.query.id = meshcookie.m; }
// Fetch the mesh object
var mesh = obj.meshes['mesh/' + domain.id + '/' + req.query.id];
if (mesh == null) { return null; }
// If needed, check if this user has rights to do this
if ((obj.parent.config.settings != null) && ((obj.parent.config.settings.lockagentdownload == true) || (domain.lockagentdownload == true))) {
if ((domain.id != mesh.domain) || ((obj.GetMeshRights(req.session.userid, mesh) & 1) == 0)) { return null; }
}
var meshidhex = Buffer.from(req.query.id.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
var serveridhex = Buffer.from(obj.agentCertificateHashBase64.replace(/\@/g, '+').replace(/\$/g, '/'), 'base64').toString('hex').toUpperCase();
// Get the agent connection server name
var serverName = obj.getWebServerName(domain);
if (typeof obj.args.agentaliasdns == 'string') { serverName = obj.args.agentaliasdns; }
// Build the agent connection URL. If we are using a sub-domain or one with a DNS, we need to craft the URL correctly.
var xdomain = (domain.dns == null) ? domain.id : '';
if (xdomain != '') xdomain += '/';
var meshsettings = 'MeshName=' + mesh.name + '\r\nMeshType=' + mesh.mtype + '\r\nMeshID=0x' + meshidhex + '\r\nServerID=' + serveridhex + '\r\n';
var httpsPort = ((obj.args.aliasport == null) ? obj.args.port : obj.args.aliasport); // Use HTTPS alias port is specified
if (obj.args.agentport != null) { httpsPort = obj.args.agentport; } // If an agent only port is enabled, use that.
if (obj.args.agentaliasport != null) { httpsPort = obj.args.agentaliasport; } // If an agent alias port is specified, use that.
if (obj.args.lanonly != true) { meshsettings += 'MeshServer=ws' + (obj.args.notls ? '' : 's') + '://' + serverName + ':' + httpsPort + '/' + xdomain + 'agent.ashx\r\n'; } else {
meshsettings += 'MeshServer=local\r\n';
if ((obj.args.localdiscovery != null) && (typeof obj.args.localdiscovery.key == 'string') && (obj.args.localdiscovery.key.length > 0)) { meshsettings += 'DiscoveryKey=' + obj.args.localdiscovery.key + '\r\n'; }
}
if ((req.query.tag != null) && (typeof req.query.tag == 'string') && (obj.common.isAlphaNumeric(req.query.tag) == true)) { meshsettings += 'Tag=' + req.query.tag + '\r\n'; }
if ((req.query.installflags != null) && (req.query.installflags != 0) && (parseInt(req.query.installflags) == req.query.installflags)) { meshsettings += 'InstallFlags=' + parseInt(req.query.installflags) + '\r\n'; }
if ((domain.agentnoproxy === true) || (obj.args.lanonly == true)) { meshsettings += 'ignoreProxyFile=1\r\n'; }
if (obj.args.agentconfig) { for (var i in obj.args.agentconfig) { meshsettings += obj.args.agentconfig[i] + '\r\n'; } }
if (domain.agentconfig) { for (var i in domain.agentconfig) { meshsettings += domain.agentconfig[i] + '\r\n'; } }
return meshsettings;
}
// Handle a request to download a mesh settings
obj.handleMeshSettingsRequest = function (req, res) {
const domain = getDomain(req);
if (domain == null) { return; }
//if ((domain.id !== '') || (!req.session) || (req.session == null) || (!req.session.userid)) { res.sendStatus(401); return; }
var meshsettings = getMshFromRequest(req, res, domain);
if (meshsettings == null) { res.sendStatus(401); return; }
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="meshagent.msh"' });
res.send(meshsettings);
};
// Handle a request for power events
obj.handleDevicePowerEvents = function (req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
if ((domain.id !== '') || (!req.session) || (req.session == null) || (!req.session.userid) || (req.query.id == null) || (typeof req.query.id != 'string')) { res.sendStatus(401); return; }
var x = req.query.id.split('/');
var user = obj.users[req.session.userid];
if ((x.length != 3) || (x[0] != 'node') || (x[1] != domain.id) || (user == null) || (user.links == null)) { res.sendStatus(401); return; }
obj.db.Get(req.query.id, function (err, docs) {
if (docs.length != 1) {
res.sendStatus(401);
} else {
var node = docs[0];
// Check if we have right to this node
if (obj.GetNodeRights(user, node.meshid, node._id) == 0) { res.sendStatus(401); return; }
// Get the list of power events and send them
res.set({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Content-Type': 'text/csv', 'Content-Disposition': 'attachment; filename="powerevents.csv"' });
obj.db.getPowerTimeline(node._id, function (err, docs) {
var xevents = ['Time, State, Previous State'], prevState = 0;
for (var i in docs) {
if (docs[i].power != prevState) {
prevState = docs[i].power;
if (docs[i].oldPower != null) {
xevents.push(docs[i].time.toString() + ',' + docs[i].power + ',' + docs[i].oldPower);
} else {
xevents.push(docs[i].time.toString() + ',' + docs[i].power);
}
}
}
res.send(xevents.join('\r\n'));
});
}
});
}
if (parent.pluginHandler != null) {
// Handle a plugin admin request
obj.handlePluginAdminReq = function (req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((!req.session) || (req.session == null) || (!req.session.userid)) { res.sendStatus(401); return; }
var user = obj.users[req.session.userid];
if (user == null) { res.sendStatus(401); return; }
parent.pluginHandler.handleAdminReq(req, res, user, obj);
}
obj.handlePluginAdminPostReq = function (req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((!req.session) || (req.session == null) || (!req.session.userid)) { res.sendStatus(401); return; }
var user = obj.users[req.session.userid];
if (user == null) { res.sendStatus(401); return; }
parent.pluginHandler.handleAdminPostReq(req, res, user, obj);
}
obj.handlePluginJS = function (req, res) {
const domain = checkUserIpAddress(req, res);
if (domain == null) { return; }
if ((!req.session) || (req.session == null) || (!req.session.userid)) { res.sendStatus(401); return; }
var user = obj.users[req.session.userid];
if (user == null) { res.sendStatus(401); return; }
parent.pluginHandler.refreshJS(req, res);
}
}
// Starts the HTTPS server, this should be called after the user/mesh tables are loaded
function serverStart() {
// Start the server, only after users and meshes are loaded from the database.
if (obj.args.notls || obj.args.tlsoffload) {
// Setup the HTTP server without TLS
obj.expressWs = require('express-ws')(obj.app, null, { wsOptions: { perMessageDeflate: (args.wscompression === true) } });
} else {
// Setup the HTTP server with TLS, use only TLS 1.2 and higher with perfect forward secrecy (PFS).
//const tlsOptions = { cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.web.ca, rejectUnauthorized: true, ciphers: "HIGH:!aNULL:!eNULL:!EXPORT:!RSA:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA", secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_COMPRESSION | constants.SSL_OP_CIPHER_SERVER_PREFERENCE | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 }; // This does not work with TLS 1.3
const tlsOptions = { cert: obj.certificates.web.cert, key: obj.certificates.web.key, ca: obj.certificates.web.ca, rejectUnauthorized: true, ciphers: "HIGH:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_8_SHA256:TLS_AES_128_CCM_SHA256:TLS_CHACHA20_POLY1305_SHA256", secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_COMPRESSION | constants.SSL_OP_CIPHER_SERVER_PREFERENCE | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 };
if (obj.tlsSniCredentials != null) { tlsOptions.SNICallback = TlsSniCallback; } // We have multiple web server certificate used depending on the domain name
obj.tlsServer = require('https').createServer(tlsOptions, obj.app);
obj.tlsServer.on('secureConnection', function () { /*console.log('tlsServer secureConnection');*/ });
obj.tlsServer.on('error', function (err) { console.log('tlsServer error', err); });
//obj.tlsServer.on('tlsClientError', function (err) { console.log('tlsClientError', err); });
obj.tlsServer.on('newSession', function (id, data, cb) { if (tlsSessionStoreCount > 1000) { tlsSessionStoreCount = 0; tlsSessionStore = {}; } tlsSessionStore[id.toString('hex')] = data; tlsSessionStoreCount++; cb(); });
obj.tlsServer.on('resumeSession', function (id, cb) { cb(null, tlsSessionStore[id.toString('hex')] || null); });
obj.expressWs = require('express-ws')(obj.app, obj.tlsServer, { wsOptions: { perMessageDeflate: (args.wscompression === true) } });
}
// Start a second agent-only server if needed
if (obj.args.agentport) {
var agentPortTls = true;
if ((obj.args.notls == 1) || (obj.args.notls == true)) { agentPortTls = false; }
if (obj.args.tlsoffload != null) { agentPortTls = false; }
if (typeof obj.args.agentporttls == 'boolean') { agentPortTls = obj.args.agentporttls; }
if (obj.certificates.webdefault == null) { agentPortTls = false; }
if (agentPortTls == false) {
// Setup the HTTP server without TLS
obj.expressWsAlt = require('express-ws')(obj.agentapp, null, { wsOptions: { perMessageDeflate: (args.wscompression === true) } });
} else {
// Setup the agent HTTP server with TLS, use only TLS 1.2 and higher with perfect forward secrecy (PFS).
// If TLS is used on the agent port, we always use the default TLS certificate.
const tlsOptions = { cert: obj.certificates.webdefault.cert, key: obj.certificates.webdefault.key, ca: obj.certificates.webdefault.ca, rejectUnauthorized: true, ciphers: "HIGH:TLS_AES_256_GCM_SHA384:TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_8_SHA256:TLS_AES_128_CCM_SHA256:TLS_CHACHA20_POLY1305_SHA256", secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_COMPRESSION | constants.SSL_OP_CIPHER_SERVER_PREFERENCE | constants.SSL_OP_NO_TLSv1 | constants.SSL_OP_NO_TLSv1_1 };
obj.tlsAltServer = require('https').createServer(tlsOptions, obj.agentapp);
obj.tlsAltServer.on('secureConnection', function () { /*console.log('tlsAltServer secureConnection');*/ });
obj.tlsAltServer.on('error', function (err) { console.log('tlsAltServer error', err); });
//obj.tlsAltServer.on('tlsClientError', function (err) { console.log('tlsClientError', err); });
obj.tlsAltServer.on('newSession', function (id, data, cb) { if (tlsSessionStoreCount > 1000) { tlsSessionStoreCount = 0; tlsSessionStore = {}; } tlsSessionStore[id.toString('hex')] = data; tlsSessionStoreCount++; cb(); });
obj.tlsAltServer.on('resumeSession', function (id, cb) { cb(null, tlsSessionStore[id.toString('hex')] || null); });
obj.expressWsAlt = require('express-ws')(obj.agentapp, obj.tlsAltServer, { wsOptions: { perMessageDeflate: (args.wscompression === true) } });
}
}
// Setup middleware
obj.app.engine('handlebars', obj.exphbs({ defaultLayout: null })); // defaultLayout: 'main'
obj.app.set('view engine', 'handlebars');
if (obj.args.trustedproxy) { obj.app.set('trust proxy', obj.args.trustedproxy); } // Reverse proxy should add the "X-Forwarded-*" headers
else if (typeof obj.args.tlsoffload == 'object') { obj.app.set('trust proxy', obj.args.tlsoffload); } // Reverse proxy should add the "X-Forwarded-*" headers
obj.app.use(obj.bodyParser.urlencoded({ extended: false }));
var sessionOptions = {
name: 'xid', // Recommended security practice to not use the default cookie name
httpOnly: true,
keys: [obj.args.sessionkey], // If multiple instances of this server are behind a load-balancer, this secret must be the same for all instances
secure: ((obj.args.notls != true) && (obj.args.tlsoffload == null)) // Use this cookie only over TLS (Check this: https://expressjs.com/en/guide/behind-proxies.html)
}
if (obj.args.sessionsamesite != null) { sessionOptions.sameSite = obj.args.sessionsamesite; } else { sessionOptions.sameSite = 'strict'; }
if (obj.args.sessiontime != null) { sessionOptions.maxAge = (obj.args.sessiontime * 60 * 1000); }
obj.app.use(obj.session(sessionOptions));
// Add HTTP security headers to all responses
obj.app.use(function (req, res, next) {
// Set the real IP address of the request
// If a trusted reverse-proxy is sending us the remote IP address, use it.
const ipex = (req.ip.startsWith('::ffff:')) ? req.ip.substring(7) : req.ip;
if (
(obj.args.trustedproxy === true) ||
((typeof obj.args.trustedproxy == 'object') && (obj.args.trustedproxy.indexOf(ipex) >= 0)) ||
((typeof obj.args.tlsoffload == 'object') && (obj.args.tlsoffload.indexOf(ipex) >= 0))
) {
if (req.headers['cf-connecting-ip']) { // Use CloudFlare IP address if present
req.clientIp = req.headers['cf-connecting-ip'].split(',')[0].trim();
} else if (req.headers['x-forwarded-for']) {
req.clientIp = req.headers['x-forwarded-for'].split(',')[0].trim();
} else if (req.headers['x-real-ip']) {
req.clientIp = req.headers['x-real-ip'].split(',')[0].trim();
} else {
req.clientIp = ipex;
}
} else {
req.clientIp = ipex;
}
// Get the domain for this request
const domain = req.xdomain = getDomain(req);
parent.debug('webrequest', '(' + req.clientIp + ') ' + req.url);
// Skip the rest is this is an agent connection
if ((req.url.indexOf('/meshrelay.ashx/.websocket') >= 0) || (req.url.indexOf('/agent.ashx/.websocket') >= 0)) { next(); return; }
// If this domain has configured headers, use them.
// Example headers: { 'Strict-Transport-Security': 'max-age=360000;includeSubDomains' };
// { 'Referrer-Policy': 'no-referrer', 'x-frame-options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src http: ws: data: 'self';script-src http: 'unsafe-inline';style-src http: 'unsafe-inline'" };
if ((domain != null) && (domain.httpheaders != null) && (typeof domain.httpheaders == 'object')) {
res.set(domain.httpheaders);
} else {
// Use default security headers
var geourl = (domain.geolocation ? ' *.openstreetmap.org' : '');
var selfurl = ((args.notls !== true) ? (' wss://' + req.headers.host) : (' ws://' + req.headers.host));
var headers = {
'Referrer-Policy': 'no-referrer',
'X-XSS-Protection': '1; mode=block',
'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': "default-src 'none'; font-src 'self'; script-src 'self' 'unsafe-inline'; connect-src 'self'" + geourl + selfurl + "; img-src 'self'" + geourl + " data:; style-src 'self' 'unsafe-inline'; frame-src 'self' mcrouter:; media-src 'self'; form-action 'self'"
};
if ((parent.config.settings.allowframing !== true) && (typeof parent.config.settings.allowframing !== 'string')) { headers['X-Frame-Options'] = 'sameorigin'; }
res.set(headers);
}
// Check the session if bound to the external IP address
if ((req.session.ip != null) && (req.clientIp != null) && (req.session.ip != req.clientIp)) { req.session = {}; }
// Extend the session time by forcing a change to the session every minute.
if (req.session.userid != null) { req.session.nowInMinutes = Math.floor(Date.now() / 60e3); } else { delete req.session.nowInMinutes; }
// Detect if this is a file sharing domain, if so, just share files.
if ((domain != null) && (domain.share != null)) {
var rpath;
if (domain.dns == null) { rpath = req.url.split('/'); rpath.splice(1, 1); rpath = rpath.join('/'); } else { rpath = req.url; }
if ((req.headers != null) && (req.headers.upgrade)) {
// If this is a websocket, stop here.
res.sendStatus(404);
} else {
// Check if the file exists, if so, serve it.
obj.fs.exists(obj.path.join(domain.share, rpath), function (exists) { if (exists == true) { res.sendfile(rpath, { root: domain.share }); } else { res.sendStatus(404); } });
}
} else {
//if (parent.config.settings.accesscontrolalloworigin != null) { headers['Access-Control-Allow-Origin'] = parent.config.settings.accesscontrolalloworigin; }
return next();
}
});
if (obj.agentapp) {
// Add HTTP security headers to all responses
obj.agentapp.use(function (req, res, next) {
// Set the real IP address of the request
// If a trusted reverse-proxy is sending us the remote IP address, use it.
const ipex = (req.ip.startsWith('::ffff:')) ? req.ip.substring(7) : req.ip;
if (
(obj.args.trustedproxy === true) ||
((typeof obj.args.trustedproxy == 'object') && (obj.args.trustedproxy.indexOf(ipex) >= 0)) ||
((typeof obj.args.tlsoffload == 'object') && (obj.args.tlsoffload.indexOf(ipex) >= 0))
) {
if (req.headers['cf-connecting-ip']) { // Use CloudFlare IP address if present
req.clientIp = req.headers['cf-connecting-ip'].split(',')[0].trim();
} else if (req.headers['x-forwarded-for']) {
req.clientIp = req.headers['x-forwarded-for'].split(',')[0].trim();
} else if (req.headers['x-real-ip']) {
req.clientIp = req.headers['x-real-ip'].split(',')[0].trim();
} else {
req.clientIp = ipex;
}
} else {
req.clientIp = ipex;
}
// Get the domain for this request
const domain = req.xdomain = getDomain(req);
parent.debug('webrequest', '(' + req.clientIp + ') AgentPort: ' + req.url);
res.removeHeader('X-Powered-By');
return next();
});
}
// Setup all HTTP handlers
if (parent.multiServer != null) { obj.app.ws('/meshserver.ashx', function (ws, req) { parent.multiServer.CreatePeerInServer(parent.multiServer, ws, req); }); }
for (var i in parent.config.domains) {
if (parent.config.domains[i].dns != null) { continue; } // This is a subdomain with a DNS name, no added HTTP bindings needed.
var domain = parent.config.domains[i];
var url = domain.url;
obj.app.get(url, handleRootRequest);
obj.app.post(url, handleRootPostRequest);
obj.app.get(url + 'refresh.ashx', function (req, res) { res.sendStatus(200); });
obj.app.get(url + 'backup.zip', handleBackupRequest);
obj.app.post(url + 'restoreserver.ashx', handleRestoreRequest);
obj.app.get(url + 'terms', handleTermsRequest);
obj.app.get(url + 'xterm', handleXTermRequest);
obj.app.post(url + 'login', handleLoginRequest);
obj.app.post(url + 'tokenlogin', handleLoginRequest);
obj.app.get(url + 'logout', handleLogoutRequest);
obj.app.get(url + 'MeshServerRootCert.cer', handleRootCertRequest);
obj.app.get(url + 'mescript.ashx', handleMeScriptRequest);
obj.app.post(url + 'changepassword', handlePasswordChangeRequest);
obj.app.post(url + 'deleteaccount', handleDeleteAccountRequest);
obj.app.post(url + 'createaccount', handleCreateAccountRequest);
obj.app.post(url + 'resetpassword', handleResetPasswordRequest);
obj.app.post(url + 'resetaccount', handleResetAccountRequest);
obj.app.get(url + 'checkmail', handleCheckMailRequest);
obj.app.get(url + 'agentinvite', handleAgentInviteRequest);
obj.app.post(url + 'amtevents.ashx', obj.handleAmtEventRequest);
obj.app.get(url + 'meshagents', obj.handleMeshAgentRequest);
obj.app.get(url + 'messenger', handleMessengerRequest);
obj.app.get(url + 'meshosxagent', obj.handleMeshOsxAgentRequest);
obj.app.get(url + 'meshsettings', obj.handleMeshSettingsRequest);
obj.app.get(url + 'devicepowerevents.ashx', obj.handleDevicePowerEvents);
obj.app.get(url + 'downloadfile.ashx', handleDownloadFile);
obj.app.post(url + 'uploadfile.ashx', handleUploadFile);
obj.app.post(url + 'uploadmeshcorefile.ashx', handleUploadMeshCoreFile);
obj.app.get(url + 'userfiles/*', handleDownloadUserFiles);
obj.app.ws(url + 'echo.ashx', handleEchoWebSocket);
obj.app.ws(url + 'apf.ashx', function (ws, req) { obj.parent.apfserver.onConnection(ws); })
obj.app.get(url + 'webrelay.ashx', function (req, res) { res.send('Websocket connection expected'); });
obj.app.get(url + 'health.ashx', function (req, res) { res.send('ok'); }); // TODO: Perform more server checking.
obj.app.ws(url + 'webrelay.ashx', function (ws, req) { PerformWSSessionAuth(ws, req, false, handleRelayWebSocket); });
obj.app.ws(url + 'webider.ashx', function (ws, req) { PerformWSSessionAuth(ws, req, false, function (ws1, req1, domain, user, cookie) { obj.meshIderHandler.CreateAmtIderSession(obj, obj.db, ws1, req1, obj.args, domain, user); }); });
obj.app.ws(url + 'control.ashx', function (ws, req) { PerformWSSessionAuth(ws, req, false, function (ws1, req1, domain, user, cookie) { obj.meshUserHandler.CreateMeshUser(obj, obj.db, ws1, req1, obj.args, domain, user); }); });
obj.app.ws(url + 'devicefile.ashx', function (ws, req) { obj.meshDeviceFileHandler.CreateMeshDeviceFile(obj, ws, null, req, domain); });
obj.app.get(url + 'devicefile.ashx', handleDeviceFile);
obj.app.get(url + 'logo.png', handleLogoRequest);
obj.app.post(url + 'translations', handleTranslationsRequest);
obj.app.get(url + 'welcome.jpg', handleWelcomeImageRequest);
obj.app.get(url + 'recordings.ashx', handleGetRecordings);
obj.app.get(url + 'player.htm', handlePlayerRequest);
obj.app.get(url + 'player', handlePlayerRequest);
obj.app.get(url + 'desktop', handleDesktopRequest);
obj.app.ws(url + 'amtactivate', handleAmtActivateWebSocket);
obj.app.ws(url + 'agenttransfer.ashx', handleAgentFileTransfer); // Setup agent to/from server file transfer handler
obj.app.ws(url + 'meshrelay.ashx', function (ws, req) {
PerformWSSessionAuth(ws, req, true, function (ws1, req1, domain, user, cookie) {
if (((parent.config.settings.desktopmultiplex === true) || (domain.desktopmultiplex === true)) && (req.query.p == 2)) {
obj.meshDesktopMultiplexHandler.CreateMeshRelay(obj, ws1, req1, domain, user, cookie); // Desktop multiplexor 1-to-n
} else {
obj.meshRelayHandler.CreateMeshRelay(obj, ws1, req1, domain, user, cookie); // Normal relay 1-to-1
}
});
});
if (domain.agentinvitecodes == true) {
obj.app.get(url + 'invite', handleInviteRequest);
obj.app.post(url + 'invite', handleInviteRequest);
}
if (parent.pluginHandler != null) {
obj.app.get(url + 'pluginadmin.ashx', obj.handlePluginAdminReq);
obj.app.post(url + 'pluginadmin.ashx', obj.handlePluginAdminPostReq);
obj.app.get(url + 'pluginHandler.js', obj.handlePluginJS);
}
// Setup MSTSC.js if needed
if (domain.mstsc === true) {
obj.app.get(url + 'mstsc.html', handleMSTSCRequest);
obj.app.ws(url + 'mstsc/relay.ashx', function (ws, req) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'mstsc: failed checks.'); try { ws.close(); } catch (e) { } return; }
require('./mstsc.js').CreateMstscRelay(obj, obj.db, ws, req, obj.args, domain);
});
}
// Setup auth strategies using passport if needed
if (typeof domain.authstrategies == 'object') {
const passport = domain.passport = require('passport');
passport.serializeUser(function (user, done) { done(null, user.sid); });
passport.deserializeUser(function (sid, done) { done(null, { sid: sid }); });
obj.app.use(passport.initialize());
//obj.app.use(passport.session());
// Twitter
if ((typeof domain.authstrategies.twitter == 'object') && (typeof domain.authstrategies.twitter.clientid == 'string') && (typeof domain.authstrategies.twitter.clientsecret == 'string')) {
const TwitterStrategy = require('passport-twitter');
var options = { consumerKey: domain.authstrategies.twitter.clientid, consumerSecret: domain.authstrategies.twitter.clientsecret };
if (typeof domain.authstrategies.twitter.callbackurl == 'string') { options.callbackURL = domain.authstrategies.twitter.callbackurl; } else { options.callbackURL = url + 'auth-twitter-callback'; }
parent.debug('web', 'Adding Twitter SSO with options: ' + JSON.stringify(options));
passport.use(new TwitterStrategy(options,
function (token, tokenSecret, profile, cb) {
parent.debug('web', 'Twitter profile: ' + JSON.stringify(profile));
var user = { sid: '~twitter:' + profile.id, name: profile.displayName, strategy: 'twitter' };
if ((typeof profile.emails == 'object') && (profile.emails[0] != null) && (typeof profile.emails[0].value == 'string')) { user.email = profile.emails[0].value; }
return cb(null, user);
}
));
obj.app.get(url + 'auth-twitter', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('twitter')(req, res, function (err) { console.log('c1', err, req.session); next(); });
});
obj.app.get(url + 'auth-twitter-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
if ((Object.keys(req.session).length == 0) && (req.query.nmr == null)) {
// This is an empty session likely due to the 302 redirection, redirect again (this is a bit of a hack).
var url = req.url;
if (url.indexOf('?') >= 0) { url += '&nmr=1'; } else { url += '?nmr=1'; } // Add this to the URL to prevent redirect loop.
res.set('Content-Type', 'text/html');
res.end('<html><head><meta http-equiv="refresh" content=0;url="' + url + '"></head><body></body></html>');
} else {
domain.passport.authenticate('twitter', { failureRedirect: '/' })(req, res, function (err) { if (err != null) { console.log(err); } next(); });
}
}, handleStrategyLogin);
}
// Google
if ((typeof domain.authstrategies.google == 'object') && (typeof domain.authstrategies.google.clientid == 'string') && (typeof domain.authstrategies.google.clientsecret == 'string')) {
const GoogleStrategy = require('passport-google-oauth20');
var options = { clientID: domain.authstrategies.google.clientid, clientSecret: domain.authstrategies.google.clientsecret };
if (typeof domain.authstrategies.google.callbackurl == 'string') { options.callbackURL = domain.authstrategies.google.callbackurl; } else { options.callbackURL = url + 'auth-google-callback'; }
parent.debug('web', 'Adding Google SSO with options: ' + JSON.stringify(options));
passport.use(new GoogleStrategy(options,
function (token, tokenSecret, profile, cb) {
parent.debug('web', 'Google profile: ' + JSON.stringify(profile));
var user = { sid: '~google:' + profile.id, name: profile.displayName, strategy: 'google' };
if ((typeof profile.emails == 'object') && (profile.emails[0] != null) && (typeof profile.emails[0].value == 'string') && (profile.emails[0].verified == true)) { user.email = profile.emails[0].value; }
return cb(null, user);
}
));
obj.app.get(url + 'auth-google', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('google', { scope: ['profile', 'email'] })(req, res, next);
});
obj.app.get(url + 'auth-google-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('google', { failureRedirect: '/' })(req, res, function (err) { if (err != null) { console.log(err); } next(); });
}, handleStrategyLogin);
}
// Github
if ((typeof domain.authstrategies.github == 'object') && (typeof domain.authstrategies.github.clientid == 'string') && (typeof domain.authstrategies.github.clientsecret == 'string')) {
const GitHubStrategy = require('passport-github2');
var options = { clientID: domain.authstrategies.github.clientid, clientSecret: domain.authstrategies.github.clientsecret };
if (typeof domain.authstrategies.github.callbackurl == 'string') { options.callbackURL = domain.authstrategies.github.callbackurl; } else { options.callbackURL = url + 'auth-github-callback'; }
parent.debug('web', 'Adding Github SSO with options: ' + JSON.stringify(options));
passport.use(new GitHubStrategy(options,
function (token, tokenSecret, profile, cb) {
parent.debug('web', 'Github profile: ' + JSON.stringify(profile));
var user = { sid: '~github:' + profile.id, name: profile.displayName, strategy: 'github' };
if ((typeof profile.emails == 'object') && (profile.emails[0] != null) && (typeof profile.emails[0].value == 'string')) { user.email = profile.emails[0].value; }
return cb(null, user);
}
));
obj.app.get(url + 'auth-github', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('github', { scope: ['user:email'] })(req, res, next);
});
obj.app.get(url + 'auth-github-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('github', { failureRedirect: '/' })(req, res, next);
}, handleStrategyLogin);
}
// Reddit
if ((typeof domain.authstrategies.reddit == 'object') && (typeof domain.authstrategies.reddit.clientid == 'string') && (typeof domain.authstrategies.reddit.clientsecret == 'string')) {
const RedditStrategy = require('passport-reddit');
var options = { clientID: domain.authstrategies.reddit.clientid, clientSecret: domain.authstrategies.reddit.clientsecret };
if (typeof domain.authstrategies.reddit.callbackurl == 'string') { options.callbackURL = domain.authstrategies.reddit.callbackurl; } else { options.callbackURL = url + 'auth-reddit-callback'; }
parent.debug('web', 'Adding Reddit SSO with options: ' + JSON.stringify(options));
passport.use(new RedditStrategy.Strategy(options,
function (token, tokenSecret, profile, cb) {
parent.debug('web', 'Reddit profile: ' + JSON.stringify(profile));
var user = { sid: '~reddit:' + profile.id, name: profile.name, strategy: 'reddit' };
if ((typeof profile.emails == 'object') && (profile.emails[0] != null) && (typeof profile.emails[0].value == 'string')) { user.email = profile.emails[0].value; }
return cb(null, user);
}
));
obj.app.get(url + 'auth-reddit', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('reddit', { state: obj.parent.encodeCookie({ 'p': 'reddit' }, obj.parent.loginCookieEncryptionKey), duration: 'permanent' })(req, res, next);
});
obj.app.get(url + 'auth-reddit-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
if ((Object.keys(req.session).length == 0) && (req.query.nmr == null)) {
// This is an empty session likely due to the 302 redirection, redirect again (this is a bit of a hack).
var url = req.url;
if (url.indexOf('?') >= 0) { url += '&nmr=1'; } else { url += '?nmr=1'; } // Add this to the URL to prevent redirect loop.
res.set('Content-Type', 'text/html');
res.end('<html><head><meta http-equiv="refresh" content=0;url="' + url + '"></head><body></body></html>');
} else {
if (req.query.state != null) {
var c = obj.parent.decodeCookie(req.query.state, obj.parent.loginCookieEncryptionKey, 10); // 10 minute timeout
if ((c != null) && (c.p == 'reddit')) { domain.passport.authenticate('reddit', { failureRedirect: '/' })(req, res, next); return; }
}
next();
}
}, handleStrategyLogin);
}
// Azure
if ((typeof domain.authstrategies.azure == 'object') && (typeof domain.authstrategies.azure.clientid == 'string') && (typeof domain.authstrategies.azure.clientsecret == 'string')) {
const AzureOAuth2Strategy = require('passport-azure-oauth2');
var options = { clientID: domain.authstrategies.azure.clientid, clientSecret: domain.authstrategies.azure.clientsecret, tenant: domain.authstrategies.azure.tenantid };
if (typeof domain.authstrategies.azure.callbackurl == 'string') { options.callbackURL = domain.authstrategies.azure.callbackurl; } else { options.callbackURL = url + 'auth-azure-callback'; }
parent.debug('web', 'Adding Azure SSO with options: ' + JSON.stringify(options));
passport.use('azure', new AzureOAuth2Strategy(options,
function (accessToken, refreshtoken, params, profile, done) {
var userex = null;
try { userex = require('jwt-simple').decode(params.id_token, "", true); } catch (ex) { }
parent.debug('web', 'Azure profile: ' + JSON.stringify(userex));
var user = null;
if (userex != null) {
var user = { sid: '~azure:' + userex.unique_name, name: userex.name, strategy: 'azure' };
if (typeof userex.email == 'string') { user.email = userex.email; }
}
return done(null, user);
}
));
obj.app.get(url + 'auth-azure', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('azure', { state: obj.parent.encodeCookie({ 'p': 'azure' }, obj.parent.loginCookieEncryptionKey) })(req, res, next);
});
obj.app.get(url + 'auth-azure-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
if ((Object.keys(req.session).length == 0) && (req.query.nmr == null)) {
// This is an empty session likely due to the 302 redirection, redirect again (this is a bit of a hack).
var url = req.url;
if (url.indexOf('?') >= 0) { url += '&nmr=1'; } else { url += '?nmr=1'; } // Add this to the URL to prevent redirect loop.
res.set('Content-Type', 'text/html');
res.end('<html><head><meta http-equiv="refresh" content=0;url="' + url + '"></head><body></body></html>');
} else {
if (req.query.state != null) {
var c = obj.parent.decodeCookie(req.query.state, obj.parent.loginCookieEncryptionKey, 10); // 10 minute timeout
if ((c != null) && (c.p == 'azure')) { domain.passport.authenticate('azure', { failureRedirect: '/' })(req, res, next); return; }
}
next();
}
}, handleStrategyLogin);
}
// Generic SAML
if (typeof domain.authstrategies.saml == 'object') {
if ((typeof domain.authstrategies.saml.cert != 'string') || (typeof domain.authstrategies.saml.idpurl != 'string')) {
console.log('ERROR: Missing SAML configuration.');
} else {
var cert = obj.fs.readFileSync(obj.path.join(obj.parent.datapath, domain.authstrategies.saml.cert));
if (cert == null) {
console.log('ERROR: Unable to read SAML IdP certificate: ' + domain.authstrategies.saml.cert);
} else {
var options = { entryPoint: domain.authstrategies.saml.idpurl, issuer: 'meshcentral' };
if (typeof domain.authstrategies.saml.callbackurl == 'string') { options.callbackUrl = domain.authstrategies.saml.callbackurl; } else { options.callbackURL = url + 'auth-saml-callback'; }
if (domain.authstrategies.saml.disablerequestedauthncontext != null) { options.disableRequestedAuthnContext = domain.authstrategies.saml.disablerequestedauthncontext; }
parent.debug('web', 'Adding SAML SSO with options: ' + JSON.stringify(options));
if (typeof domain.authstrategies.saml.entityid == 'string') { options.issuer = domain.authstrategies.saml.entityid; }
options.cert = cert.toString().split('-----BEGIN CERTIFICATE-----').join('').split('-----END CERTIFICATE-----').join('');
const SamlStrategy = require('passport-saml').Strategy;
passport.use(new SamlStrategy(options,
function (profile, done) {
parent.debug('web', 'SAML profile: ' + JSON.stringify(profile));
if (typeof profile.nameID != 'string') { return done(); }
var user = { sid: '~saml:' + profile.nameID, name: profile.nameID, strategy: 'saml' };
if ((typeof profile.firstname == 'string') && (typeof profile.lastname == 'string')) { user.name = profile.firstname + ' ' + profile.lastname; }
if (typeof profile.email == 'string') { user.email = profile.email; }
return done(null, user);
}
));
obj.app.get(url + 'auth-saml', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('saml', { failureRedirect: '/', failureFlash: true })(req, res, next);
});
obj.app.post(url + 'auth-saml-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('saml', { failureRedirect: '/', failureFlash: true })(req, res, next);
}, handleStrategyLogin);
}
}
}
// Intel SAML
if (typeof domain.authstrategies.intel == 'object') {
if ((typeof domain.authstrategies.intel.cert != 'string') || (typeof domain.authstrategies.intel.idpurl != 'string')) {
console.log('ERROR: Missing Intel SAML configuration.');
} else {
var cert = obj.fs.readFileSync(obj.path.join(obj.parent.datapath, domain.authstrategies.intel.cert));
if (cert == null) {
console.log('ERROR: Unable to read Intel SAML IdP certificate: ' + domain.authstrategies.intel.cert);
} else {
var options = { entryPoint: domain.authstrategies.intel.idpurl, issuer: 'meshcentral' };
if (typeof domain.authstrategies.intel.callbackurl == 'string') { options.callbackUrl = domain.authstrategies.intel.callbackurl; } else { options.callbackUrl = url + 'auth-intel-callback'; }
if (domain.authstrategies.intel.disablerequestedauthncontext != null) { options.disableRequestedAuthnContext = domain.authstrategies.intel.disablerequestedauthncontext; }
parent.debug('web', 'Adding Intel SSO with options: ' + JSON.stringify(options));
if (typeof domain.authstrategies.intel.entityid == 'string') { options.issuer = domain.authstrategies.intel.entityid; }
options.cert = cert.toString().split('-----BEGIN CERTIFICATE-----').join('').split('-----END CERTIFICATE-----').join('');
const SamlStrategy = require('passport-saml').Strategy;
passport.use(new SamlStrategy(options,
function (profile, done) {
parent.debug('web', 'Intel profile: ' + JSON.stringify(profile));
if (typeof profile.nameID != 'string') { return done(); }
var user = { sid: '~intel:' + profile.nameID, name: profile.nameID, strategy: 'intel' };
if ((typeof profile.firstname == 'string') && (typeof profile.lastname == 'string')) { user.name = profile.firstname + ' ' + profile.lastname; }
else if ((typeof profile.FirstName == 'string') && (typeof profile.LastName == 'string')) { user.name = profile.FirstName + ' ' + profile.LastName; }
if (typeof profile.email == 'string') { user.email = profile.email; }
else if (typeof profile.EmailAddress == 'string') { user.email = profile.EmailAddress; }
return done(null, user);
}
));
obj.app.get(url + 'auth-intel', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('saml', { failureRedirect: '/', failureFlash: true })(req, res, next);
});
obj.app.post(url + 'auth-intel-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('saml', { failureRedirect: '/', failureFlash: true })(req, res, next);
}, handleStrategyLogin);
}
}
}
// JumpCloud SAML
if (typeof domain.authstrategies.jumpcloud == 'object') {
if ((typeof domain.authstrategies.jumpcloud.cert != 'string') || (typeof domain.authstrategies.jumpcloud.idpurl != 'string')) {
console.log('ERROR: Missing JumpCloud SAML configuration.');
} else {
var cert = obj.fs.readFileSync(obj.path.join(obj.parent.datapath, domain.authstrategies.jumpcloud.cert));
if (cert == null) {
console.log('ERROR: Unable to read JumpCloud IdP certificate: ' + domain.authstrategies.jumpcloud.cert);
} else {
var options = { entryPoint: domain.authstrategies.jumpcloud.idpurl, issuer: 'meshcentral' };
if (typeof domain.authstrategies.jumpcloud.callbackurl == 'string') { options.callbackUrl = domain.authstrategies.jumpcloud.callbackurl; } else { options.callbackUrl = url + 'auth-jumpcloud-callback'; }
parent.debug('web', 'Adding JumpCloud SSO with options: ' + JSON.stringify(options));
if (typeof domain.authstrategies.jumpcloud.entityid == 'string') { options.issuer = domain.authstrategies.jumpcloud.entityid; }
options.cert = cert.toString().split('-----BEGIN CERTIFICATE-----').join('').split('-----END CERTIFICATE-----').join('');
const SamlStrategy = require('passport-saml').Strategy;
passport.use(new SamlStrategy(options,
function (profile, done) {
parent.debug('web', 'JumpCloud profile: ' + JSON.stringify(profile));
if (typeof profile.nameID != 'string') { return done(); }
var user = { sid: '~jumpcloud:' + profile.nameID, name: profile.nameID, strategy: 'jumpcloud' };
if ((typeof profile.firstname == 'string') && (typeof profile.lastname == 'string')) { user.name = profile.firstname + ' ' + profile.lastname; }
if (typeof profile.email == 'string') { user.email = profile.email; }
return done(null, user);
}
));
obj.app.get(url + 'auth-jumpcloud', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('saml', { failureRedirect: '/', failureFlash: true })(req, res, next);
});
obj.app.post(url + 'auth-jumpcloud-callback', function (req, res, next) {
var domain = getDomain(req);
if (domain.passport == null) { next(); return; }
domain.passport.authenticate('saml', { failureRedirect: '/', failureFlash: true })(req, res, next);
}, handleStrategyLogin);
}
}
}
}
// Server redirects
if (parent.config.domains[i].redirects) { for (var j in parent.config.domains[i].redirects) { if (j[0] != '_') { obj.app.get(url + j, obj.handleDomainRedirect); } } }
// Server picture
obj.app.get(url + 'serverpic.ashx', function (req, res) {
// Check if we have "server.jpg" in the data folder, if so, use that.
if ((parent.configurationFiles != null) && (parent.configurationFiles['server.png'] != null)) {
res.set({ 'Content-Type': 'image/png' });
res.send(parent.configurationFiles['server.png']);
} else {
// Check if we have "server.jpg" in the data folder, if so, use that.
var p = obj.path.join(obj.parent.datapath, 'server.png');
if (obj.fs.existsSync(p)) {
// Use the data folder server picture
try { res.sendFile(p); } catch (ex) { res.sendStatus(404); }
} else {
var domain = getDomain(req);
if ((domain != null) && (domain.webpublicpath != null) && (obj.fs.existsSync(obj.path.join(domain.webpublicpath, 'images/server-256.png')))) {
// Use the domain server picture
try { res.sendFile(obj.path.join(domain.webpublicpath, 'images/server-256.png')); } catch (ex) { res.sendStatus(404); }
} else if (parent.webPublicOverridePath && obj.fs.existsSync(obj.path.join(obj.parent.webPublicOverridePath, 'images/server-256.png'))) {
// Use the override server picture
try { res.sendFile(obj.path.join(obj.parent.webPublicOverridePath, 'images/server-256.png')); } catch (ex) { res.sendStatus(404); }
} else {
// Use the default server picture
try { res.sendFile(obj.path.join(obj.parent.webPublicPath, 'images/server-256.png')); } catch (ex) { res.sendStatus(404); }
}
}
}
});
// Receive mesh agent connections
obj.app.ws(url + 'agent.ashx', function (ws, req) {
var domain = checkAgentIpAddress(ws, req);
if (domain == null) { parent.debug('web', 'Got agent connection with bad domain or blocked IP address ' + req.clientIp + ', holding.'); return; }
//console.log('Agent connect: ' + req.clientIp);
try { obj.meshAgentHandler.CreateMeshAgent(obj, obj.db, ws, req, obj.args, domain); } catch (e) { console.log(e); }
});
// Setup MQTT broker over websocket
if (obj.parent.mqttbroker != null) {
obj.app.ws(url + 'mqtt.ashx', function (ws, req) {
var domain = checkAgentIpAddress(ws, req);
if (domain == null) { parent.debug('web', 'Got agent connection with bad domain or blocked IP address ' + req.clientIp + ', holding.'); return; }
var serialtunnel = SerialTunnel();
serialtunnel.xtransport = 'ws';
serialtunnel.xdomain = domain;
serialtunnel.xip = req.clientIp;
ws.on('message', function (b) { serialtunnel.updateBuffer(Buffer.from(b, 'binary')) });
serialtunnel.forwardwrite = function (b) { ws.send(b, 'binary') }
ws.on('close', function () { serialtunnel.emit('end'); });
obj.parent.mqttbroker.handle(serialtunnel); // Pass socket wrapper to MQTT broker
});
}
// Setup the alternative agent-only port
if (obj.agentapp) {
// Receive mesh agent connections on alternate port
obj.agentapp.ws(url + 'agent.ashx', function (ws, req) {
var domain = checkAgentIpAddress(ws, req);
if (domain == null) { parent.debug('web', 'Got agent connection with bad domain or blocked IP address ' + req.clientIp + ', holding.'); return; }
//console.log('Agent connect: ' + req.clientIp);
try { obj.meshAgentHandler.CreateMeshAgent(obj, obj.db, ws, req, obj.args, domain); } catch (e) { console.log(e); }
});
// Setup mesh relay on alternative agent-only port
obj.agentapp.ws(url + 'meshrelay.ashx', function (ws, req) {
PerformWSSessionAuth(ws, req, true, function (ws1, req1, domain, user, cookie) {
if (((parent.config.settings.desktopmultiplex === true) || (domain.desktopmultiplex === true)) && (req.query.p == 2)) {
obj.meshDesktopMultiplexHandler.CreateMeshRelay(obj, ws1, req1, domain, user, cookie); // Desktop multiplexor 1-to-n
} else {
obj.meshRelayHandler.CreateMeshRelay(obj, ws1, req1, domain, user, cookie); // Normal relay 1-to-1
}
});
});
// Setup agent to/from server file transfer handler
obj.agentapp.ws(url + 'agenttransfer.ashx', handleAgentFileTransfer); // Setup agent to/from server file transfer handler
}
// Indicates to ExpressJS that the override public folder should be used to serve static files.
if (parent.config.domains[i].webpublicpath != null) {
// Use domain public path
obj.app.use(url, obj.express.static(parent.config.domains[i].webpublicpath));
} else if (obj.parent.webPublicOverridePath != null) {
// Use override path
obj.app.use(url, obj.express.static(obj.parent.webPublicOverridePath));
}
// Indicates to ExpressJS that the default public folder should be used to serve static files.
obj.app.use(url, obj.express.static(obj.parent.webPublicPath));
// Start regular disconnection list flush every 2 minutes.
obj.wsagentsDisconnectionsTimer = setInterval(function () { obj.wsagentsDisconnections = {}; }, 120000);
}
// Handle 404 error
if (obj.args.nice404 !== false) {
obj.app.use(function (req, res, next) {
parent.debug('web', '404 Error ' + req.url);
var domain = getDomain(req);
if ((domain == null) || (domain.auth == 'sspi')) { res.sendStatus(404); return; }
if ((domain.loginkey != null) && (domain.loginkey.indexOf(req.query.key) == -1)) { res.sendStatus(404); return; } // Check 3FA URL key
res.status(404).render(getRenderPage('error404', req, domain), getRenderArgs({}, req, domain));
});
}
// Start server on a free port.
CheckListenPort(obj.args.port, obj.args.portbind, StartWebServer);
// Start on a second agent-only alternative port if needed.
if (obj.args.agentport) { CheckListenPort(obj.args.agentport, obj.args.agentportbind, StartAltWebServer); }
}
// Authenticates a session and forwards
function PerformWSSessionAuth(ws, req, noAuthOk, func) {
// Check if this is a banned ip address
if (obj.checkAllowLogin(req) == false) { parent.debug('web', 'WSERROR: Banned connection.'); try { ws.send(JSON.stringify({ action: 'close', cause: 'banned', msg: 'banned-1' })); ws.close(); } catch (e) { } return; }
try {
// Hold this websocket until we are ready.
ws._socket.pause();
// Check IP filtering and domain
var domain = null;
if (noAuthOk == true) {
domain = getDomain(req);
if (domain == null) { parent.debug('web', 'WSERROR: Got no domain, no auth ok.'); try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'noauth-1' })); ws.close(); return; } catch (e) { } return; }
} else {
// If authentication is required, enforce IP address filtering.
domain = checkUserIpAddress(ws, req);
if (domain == null) { parent.debug('web', 'WSERROR: Got no domain, user auth required.'); return; }
}
var emailcheck = ((obj.parent.mailserver != null) && (obj.parent.certificates.CommonName != null) && (obj.parent.certificates.CommonName.indexOf('.') != -1) && (obj.args.lanonly != true) && (domain.auth != 'sspi') && (domain.auth != 'ldap'))
// A web socket session can be authenticated in many ways (Default user, session, user/pass and cookie). Check authentication here.
if ((req.query.user != null) && (req.query.pass != null)) {
// A user/pass is provided in URL arguments
obj.authenticate(req.query.user, req.query.pass, domain, function (err, userid) {
var user = obj.users[userid];
if ((err == null) && (user)) {
// Check if a 2nd factor is needed
if (checkUserOneTimePasswordRequired(domain, user, req) == true) {
// Figure out if email 2FA is allowed
var email2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (parent.mailserver != null) && (user.otpekey != null));
var sms2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false)) && (parent.smsserver != null) && (user.phone != null));
if ((typeof req.query.token != 'string') || (req.query.token == '**email**') || (req.query.token == '**sms**')) {
if ((req.query.token == '**email**') && (email2fa == true)) {
// Cause a token to be sent to the user's registered email
user.otpekey = { k: obj.common.zeroPad(getRandomEightDigitInteger(), 8), d: Date.now() };
obj.db.SetUser(user);
parent.debug('web', 'Sending 2FA email to: ' + user.email);
parent.mailserver.sendAccountLoginMail(domain, user.email, user.otpekey.k, obj.getLanguageCodes(req));
// Ask for a login token & confirm email was sent
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', email2fa: email2fa, email2fasent: true })); ws.close(); } catch (e) { }
} else if ((req.query.token == '**sms**') && (sms2fa == true)) {
// Cause a token to be sent to the user's phone number
user.otpsms = { k: obj.common.zeroPad(getRandomSixDigitInteger(), 6), d: Date.now() };
obj.db.SetUser(user);
parent.debug('web', 'Sending 2FA SMS to: ' + user.phone);
parent.smsserver.sendToken(domain, user.phone, user.otpsms.k, obj.getLanguageCodes(req));
// Ask for a login token & confirm sms was sent
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', sms2fa: sms2fa, sms2fasent: true })); ws.close(); } catch (e) { }
} else {
// Ask for a login token
parent.debug('web', 'Asking for login token');
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', email2fa: email2fa })); ws.close(); } catch (e) { }
}
} else {
checkUserOneTimePassword(req, domain, user, req.query.token, null, function (result) {
if (result == false) {
// Failed, ask for a login token again
parent.debug('web', 'Invalid login token, asking again');
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', email2fa: email2fa })); ws.close(); } catch (e) { }
} else {
// We are authenticated with 2nd factor.
// Check email verification
if (emailcheck && (user.email != null) && (user.emailVerified !== true)) {
parent.debug('web', 'Invalid login, asking for email validation');
try { ws.send(JSON.stringify({ action: 'close', cause: 'emailvalidation', msg: 'emailvalidationrequired', email2fa: email2fa, email2fasent: true })); ws.close(); } catch (e) { }
} else {
func(ws, req, domain, user);
}
}
});
}
} else {
// Check email verification
if (emailcheck && (user.email != null) && (user.emailVerified !== true)) {
parent.debug('web', 'Invalid login, asking for email validation');
try { ws.send(JSON.stringify({ action: 'close', cause: 'emailvalidation', msg: 'emailvalidationrequired', email2fa: email2fa, email2fasent: true })); ws.close(); } catch (e) { }
} else {
// We are authenticated
func(ws, req, domain, user);
}
}
} else {
// Failed to authenticate, see if a default user is active
if (obj.args.user && obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]) {
// A default user is active
func(ws, req, domain, obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]);
} else {
// If not authenticated, close the websocket connection
parent.debug('web', 'ERR: Websocket bad user/pass auth');
//obj.parent.DispatchEvent(['*', 'server-users', 'user/' + domain.id + '/' + obj.args.user.toLowerCase()], obj, { action: 'authfail', userid: 'user/' + domain.id + '/' + obj.args.user.toLowerCase(), username: obj.args.user, domain: domain.id, msg: 'Invalid user login attempt from ' + req.clientIp });
//obj.setbadLogin(req);
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'noauth-2' })); ws.close(); } catch (e) { }
}
}
});
return;
} else if ((req.query.auth != null) && (req.query.auth != '')) {
// This is a encrypted cookie authentication
var cookie = obj.parent.decodeCookie(req.query.auth, obj.parent.loginCookieEncryptionKey, 240); // Cookie with 4 hour timeout
if ((cookie == null) && (obj.parent.multiServer != null)) { cookie = obj.parent.decodeCookie(req.query.auth, obj.parent.serverKey, 240); } // Try the server key
if ((obj.args.cookieipcheck !== false) && (cookie != null) && (cookie.ip != null) && (cookie.ip != req.clientIp && (cookie.ip != req.clientIp))) { // If the cookie if binded to an IP address, check here.
parent.debug('web', 'ERR: Invalid cookie IP address, got \"' + cookie.ip + '\", expected \"' + cleanRemoteAddr(req.clientIp) + '\".');
cookie = null;
}
if ((cookie != null) && (obj.users[cookie.userid]) && (cookie.domainid == domain.id)) {
// Valid cookie, we are authenticated
func(ws, req, domain, obj.users[cookie.userid], cookie);
} else {
// This is a bad cookie, keep going anyway, maybe we have a active session that will save us.
if ((cookie != null) && (cookie.domainid != domain.id)) { parent.debug('web', 'ERR: Invalid domain, got \"' + cookie.domainid + '\", expected \"' + domain.id + '\".'); }
parent.debug('web', 'ERR: Websocket bad cookie auth (Cookie:' + (cookie != null) + '): ' + req.query.auth);
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'noauth-2' })); ws.close(); } catch (e) { }
}
return;
} else if (req.headers['x-meshauth'] != null) {
// This is authentication using a custom HTTP header
var s = req.headers['x-meshauth'].split(',');
for (var i in s) { s[i] = Buffer.from(s[i], 'base64').toString(); }
if ((s.length < 2) || (s.length > 3)) { try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'noauth-2' })); ws.close(); } catch (e) { } return; }
obj.authenticate(s[0], s[1], domain, function (err, userid) {
var user = obj.users[userid];
if ((err == null) && (user)) {
// Check if a 2nd factor is needed
if (checkUserOneTimePasswordRequired(domain, user, req) == true) {
// Figure out if email 2FA is allowed
var email2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.email2factor != false)) && (parent.mailserver != null) && (user.otpekey != null));
var sms2fa = (((typeof domain.passwordrequirements != 'object') || (domain.passwordrequirements.sms2factor != false)) && (parent.smsserver != null) && (user.phone != null));
if (s.length != 3) {
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', email2fa: email2fa, sms2fa: sms2fa })); ws.close(); } catch (e) { }
} else {
checkUserOneTimePassword(req, domain, user, s[2], null, function (result) {
if (result == false) {
if ((s[2] == '**email**') && (email2fa == true)) {
// Cause a token to be sent to the user's registered email
user.otpekey = { k: obj.common.zeroPad(getRandomEightDigitInteger(), 8), d: Date.now() };
obj.db.SetUser(user);
parent.debug('web', 'Sending 2FA email to: ' + user.email);
parent.mailserver.sendAccountLoginMail(domain, user.email, user.otpekey.k, obj.getLanguageCodes(req));
// Ask for a login token & confirm email was sent
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', email2fa: email2fa, email2fasent: true })); ws.close(); } catch (e) { }
} else if ((s[2] == '**sms**') && (sms2fa == true)) {
// Cause a token to be sent to the user's phone number
user.otpsms = { k: obj.common.zeroPad(getRandomSixDigitInteger(), 6), d: Date.now() };
obj.db.SetUser(user);
parent.debug('web', 'Sending 2FA SMS to: ' + user.phone);
parent.smsserver.sendToken(domain, user.phone, user.otpsms.k, obj.getLanguageCodes(req));
// Ask for a login token & confirm sms was sent
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', sms2fa: sms2fa, sms2fasent: true })); ws.close(); } catch (e) { }
} else {
// Ask for a login token
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'tokenrequired', email2fa: email2fa })); ws.close(); } catch (e) { }
}
} else {
// We are authenticated with 2nd factor.
// Check email verification
if (emailcheck && (user.email != null) && (user.emailVerified !== true)) {
try { ws.send(JSON.stringify({ action: 'close', cause: 'emailvalidation', msg: 'emailvalidationrequired', email2fa: email2fa, email2fasent: true })); ws.close(); } catch (e) { }
} else {
func(ws, req, domain, user);
}
}
});
}
} else {
// We are authenticated
// Check email verification
if (emailcheck && (user.email != null) && (user.emailVerified !== true)) {
try { ws.send(JSON.stringify({ action: 'close', cause: 'emailvalidation', msg: 'emailvalidationrequired', email2fa: email2fa, email2fasent: true })); ws.close(); } catch (e) { }
} else {
func(ws, req, domain, user);
}
}
} else {
// Failed to authenticate, see if a default user is active
if (obj.args.user && obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]) {
// A default user is active
func(ws, req, domain, obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]);
} else {
// If not authenticated, close the websocket connection
parent.debug('web', 'ERR: Websocket bad user/pass auth');
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'noauth-2' })); ws.close(); } catch (e) { }
}
}
});
return;
}
//console.log(req.headers['x-meshauth']);
if (obj.args.user && obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]) {
// A default user is active
func(ws, req, domain, obj.users['user/' + domain.id + '/' + obj.args.user.toLowerCase()]);
return;
} else if (req.session && (req.session.userid != null) && (req.session.domainid == domain.id) && (obj.users[req.session.userid])) {
// This user is logged in using the ExpressJS session
func(ws, req, domain, obj.users[req.session.userid]);
return;
}
if (noAuthOk != true) {
// If not authenticated, close the websocket connection
parent.debug('web', 'ERR: Websocket no auth');
try { ws.send(JSON.stringify({ action: 'close', cause: 'noauth', msg: 'noauth-4' })); ws.close(); } catch (e) { }
} else {
// Continue this session without user authentication,
// this is expected if the agent is connecting for a tunnel.
func(ws, req, domain, null);
}
} catch (e) { console.log(e); }
}
// Find a free port starting with the specified one and going up.
function CheckListenPort(port, addr, func) {
var s = obj.net.createServer(function (socket) { });
obj.tcpServer = s.listen(port, addr, function () { s.close(function () { if (func) { func(port, addr); } }); }).on('error', function (err) {
if (args.exactports) { console.error('ERROR: MeshCentral HTTPS server port ' + port + ' not available.'); process.exit(); }
else { if (port < 65535) { CheckListenPort(port + 1, addr, func); } else { if (func) { func(0); } } }
});
}
// Start the ExpressJS web server
function StartWebServer(port, addr) {
if ((port < 1) || (port > 65535)) return;
obj.args.port = port;
if (obj.tlsServer != null) {
if (obj.args.lanonly == true) {
obj.tcpServer = obj.tlsServer.listen(port, addr, function () { console.log('MeshCentral HTTPS server running on port ' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
} else {
obj.tcpServer = obj.tlsServer.listen(port, addr, function () { console.log('MeshCentral HTTPS server running on ' + certificates.CommonName + ':' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
obj.parent.updateServerState('servername', certificates.CommonName);
}
if (obj.parent.authlog) { obj.parent.authLog('https', 'Server listening on ' + ((addr != null) ? addr : '0.0.0.0') + ' port ' + port + '.'); }
obj.parent.updateServerState('https-port', port);
if (args.aliasport != null) { obj.parent.updateServerState('https-aliasport', args.aliasport); }
} else {
obj.tcpServer = obj.app.listen(port, addr, function () { console.log('MeshCentral HTTP server running on port ' + port + ((args.aliasport != null) ? (', alias port ' + args.aliasport) : '') + '.'); });
obj.parent.updateServerState('http-port', port);
if (args.aliasport != null) { obj.parent.updateServerState('http-aliasport', args.aliasport); }
}
// Check if there is a permissions problem with the ports.
if (require('os').platform() != 'win32') {
var expectedPort = obj.parent.config.settings.port ? obj.parent.config.settings.port : 443;
if ((expectedPort != port) && (port >= 1024) && (port < 1034)) {
console.log('');
console.log('WARNING: MeshCentral is running without permissions to use ports below 1025.');
console.log(' Use setcap to grant access to lower ports, or read installation guide.');
console.log('');
console.log(' sudo setcap \'cap_net_bind_service=+ep\' `which node` \r\n');
obj.parent.addServerWarning('Server running without permissions to use ports below 1025.', false);
}
}
}
// Start the ExpressJS web server on agent-only alternative port
function StartAltWebServer(port, addr) {
if ((port < 1) || (port > 65535)) return;
var agentAliasPort = null;
if (args.agentaliasport != null) { agentAliasPort = args.agentaliasport; }
if (obj.tlsAltServer != null) {
if (obj.args.lanonly == true) {
obj.tcpAltServer = obj.tlsAltServer.listen(port, addr, function () { console.log('MeshCentral HTTPS agent-only server running on port ' + port + ((agentAliasPort != null) ? (', alias port ' + agentAliasPort) : '') + '.'); });
} else {
obj.tcpAltServer = obj.tlsAltServer.listen(port, addr, function () { console.log('MeshCentral HTTPS agent-only server running on ' + certificates.CommonName + ':' + port + ((agentAliasPort != null) ? (', alias port ' + agentAliasPort) : '') + '.'); });
}
if (obj.parent.authlog) { obj.parent.authLog('https', 'Server listening on 0.0.0.0 port ' + port + '.'); }
obj.parent.updateServerState('https-agent-port', port);
} else {
obj.tcpAltServer = obj.agentapp.listen(port, addr, function () { console.log('MeshCentral HTTP agent-only server running on port ' + port + ((agentAliasPort != null) ? (', alias port ' + agentAliasPort) : '') + '.'); });
obj.parent.updateServerState('http-agent-port', port);
}
}
// Force mesh agent disconnection
obj.forceMeshAgentDisconnect = function (user, domain, nodeid, disconnectMode) {
if (nodeid == null) return;
var splitnode = nodeid.split('/');
if ((splitnode.length != 3) || (splitnode[1] != domain.id)) return; // Check that nodeid is valid and part of our domain
var agent = obj.wsagents[nodeid];
if (agent == null) return;
// Check we have agent rights
if (((obj.GetMeshRights(user, agent.dbMeshKey) & MESHRIGHT_AGENTCONSOLE) != 0) || (user.siteadmin == 0xFFFFFFFF)) { agent.close(disconnectMode); }
};
// Send the core module to the mesh agent
obj.sendMeshAgentCore = function (user, domain, nodeid, coretype, coredata) {
if (nodeid == null) return;
const splitnode = nodeid.split('/');
if ((splitnode.length != 3) || (splitnode[1] != domain.id)) return; // Check that nodeid is valid and part of our domain
// TODO: This command only works if the agent is connected on the same server. Will not work with multi server peering.
const agent = obj.wsagents[nodeid];
if (agent == null) return;
// Check we have agent rights
if (((obj.GetMeshRights(user, agent.dbMeshKey) & MESHRIGHT_AGENTCONSOLE) != 0) || (user.siteadmin == 0xFFFFFFFF)) {
if (coretype == 'clear') {
// Clear the mesh agent core
agent.agentCoreCheck = 1000; // Tell the agent object we are using a custom core.
agent.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0));
} else if (coretype == 'default') {
// Reset to default code
agent.agentCoreCheck = 0; // Tell the agent object we are using a default code
agent.send(obj.common.ShortToStr(11) + obj.common.ShortToStr(0)); // Command 11, ask for mesh core hash.
} else if (coretype == 'recovery') {
// Reset to recovery core
agent.agentCoreCheck = 1001; // Tell the agent object we are using the recovery core.
agent.send(obj.common.ShortToStr(11) + obj.common.ShortToStr(0)); // Command 11, ask for mesh core hash.
} else if (coretype == 'custom') {
agent.agentCoreCheck = 1000; // Tell the agent object we are using a custom core.
const hash = obj.crypto.createHash('sha384').update(Buffer.from(coredata, 'binary')).digest().toString('binary'); // Perform a SHA384 hash on the core module
agent.send(obj.common.ShortToStr(10) + obj.common.ShortToStr(0) + hash + coredata); // Send the code module to the agent
}
}
};
// Get the server path of a user or mesh object
function getServerRootFilePath(obj) {
if ((typeof obj != 'object') || (obj.domain == null) || (obj._id == null)) return null;
var domainname = 'domain', splitname = obj._id.split('/');
if (splitname.length != 3) return null;
if (obj.domain !== '') domainname = 'domain-' + obj.domain;
return obj.path.join(obj.filespath, domainname + "/" + splitname[0] + "-" + splitname[2]);
}
// Return true is the input string looks like an email address
function checkEmail(str) {
var x = str.split('@');
var ok = ((x.length == 2) && (x[0].length > 0) && (x[1].split('.').length > 1) && (x[1].length > 2));
if (ok == true) { var y = x[1].split('.'); for (var i in y) { if (y[i].length == 0) { ok = false; } } }
return ok;
}
/*
obj.wssessions = {}; // UserId --> Array Of Sessions
obj.wssessions2 = {}; // "UserId + SessionRnd" --> Session (Note that the SessionId is the UserId + / + SessionRnd)
obj.wsPeerSessions = {}; // ServerId --> Array Of "UserId + SessionRnd"
obj.wsPeerSessions2 = {}; // "UserId + SessionRnd" --> ServerId
obj.wsPeerSessions3 = {}; // ServerId --> UserId --> [ SessionId ]
*/
// Count sessions and event any changes
obj.recountSessions = function (changedSessionId) {
var userid, oldcount, newcount, x, serverid;
if (changedSessionId == null) {
// Recount all sessions
// Calculate the session count for all userid's
var newSessionsCount = {};
for (userid in obj.wssessions) { newSessionsCount[userid] = obj.wssessions[userid].length; }
for (serverid in obj.wsPeerSessions3) {
for (userid in obj.wsPeerSessions3[serverid]) {
x = obj.wsPeerSessions3[serverid][userid].length;
if (newSessionsCount[userid] == null) { newSessionsCount[userid] = x; } else { newSessionsCount[userid] += x; }
}
}
// See what session counts have changed, event any changes
for (userid in newSessionsCount) {
newcount = newSessionsCount[userid];
oldcount = obj.sessionsCount[userid];
if (oldcount == null) { oldcount = 0; } else { delete obj.sessionsCount[userid]; }
if (newcount != oldcount) {
x = userid.split('/');
var u = obj.users[userid];
if (u) {
var targets = ['*', 'server-users'];
if (u.groups) { for (var i in u.groups) { targets.push('server-users:' + i); } }
obj.parent.DispatchEvent(targets, obj, { action: 'wssessioncount', userid: userid, username: x[2], count: newcount, domain: x[1], nolog: 1, nopeers: 1 });
}
}
}
// If there are any counts left in the old counts, event to zero
for (userid in obj.sessionsCount) {
oldcount = obj.sessionsCount[userid];
if ((oldcount != null) && (oldcount != 0)) {
x = userid.split('/');
var u = obj.users[userid];
if (u) {
var targets = ['*', 'server-users'];
if (u.groups) { for (var i in u.groups) { targets.push('server-users:' + i); } }
obj.parent.DispatchEvent(['*'], obj, { action: 'wssessioncount', userid: userid, username: x[2], count: 0, domain: x[1], nolog: 1, nopeers: 1 })
}
}
}
// Set the new session counts
obj.sessionsCount = newSessionsCount;
} else {
// Figure out the userid
userid = changedSessionId.split('/').slice(0, 3).join('/');
// Recount only changedSessionId
newcount = 0;
if (obj.wssessions[userid] != null) { newcount = obj.wssessions[userid].length; }
for (serverid in obj.wsPeerSessions3) { if (obj.wsPeerSessions3[serverid][userid] != null) { newcount += obj.wsPeerSessions3[serverid][userid].length; } }
oldcount = obj.sessionsCount[userid];
if (oldcount == null) { oldcount = 0; }
// If the count changed, update and event
if (newcount != oldcount) {
x = userid.split('/');
var u = obj.users[userid];
if (u) {
var targets = ['*', 'server-users'];
if (u.groups) { for (var i in u.groups) { targets.push('server-users:' + i); } }
obj.parent.DispatchEvent(targets, obj, { action: 'wssessioncount', userid: userid, username: x[2], count: newcount, domain: x[1], nolog: 1, nopeers: 1 });
obj.sessionsCount[userid] = newcount;
}
}
}
};
//
// Access Control Functions
//
// Return the node and rights for a given nodeid
obj.GetNodeWithRights = function (domain, user, nodeid, func) {
// Perform user pre-validation
if ((user == null) || (nodeid == null)) { func(null, 0, false); return; } // Invalid user
if (typeof user == 'string') { user = obj.users[user]; }
if ((user == null) || (user.links == null)) { func(null, 0, false); return; } // No rights
// Perform node pre-validation
if (obj.common.validateString(nodeid, 0, 128) == false) { func(null, 0, false); return; } // Invalid nodeid
const snode = nodeid.split('/');
if ((snode.length != 3) || (snode[0] != 'node')) { func(null, 0, false); return; } // Invalid nodeid
if ((domain != null) && (snode[1] != domain.id)) { func(null, 0, false); return; } // Invalid domain
// Check that we have permissions for this node.
db.Get(nodeid, function (err, nodes) {
if ((nodes == null) || (nodes.length != 1)) { func(null, 0, false); return; } // No such nodeid
// This is a super user that can see all device groups for a given domain
if ((user.siteadmin == 0xFFFFFFFF) && (parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0) && (nodes[0].domain == user.domain)) {
func(nodes[0], 0xFFFFFFFF, true); return;
}
// Check device link
var rights = 0, visible = false, r = user.links[nodeid];
if (r != null) {
if (r.rights == 0xFFFFFFFF) { func(nodes[0], 0xFFFFFFFF, true); return; } // User has full rights thru a device link, stop here.
rights |= r.rights;
visible = true;
}
// Check device group link
r = user.links[nodes[0].meshid];
if (r != null) {
if (r.rights == 0xFFFFFFFF) { func(nodes[0], 0xFFFFFFFF, true); return; } // User has full rights thru a device group link, stop here.
rights |= r.rights;
visible = true;
}
// Check user group links
for (var i in user.links) {
if (i.startsWith('ugrp/')) {
const g = obj.userGroups[i];
if (g && (g.links != null)) {
r = g.links[nodes[0].meshid];
if (r != null) {
if (r.rights == 0xFFFFFFFF) { func(nodes[0], 0xFFFFFFFF, true); return; } // User has full rights thru a user group link, stop here.
rights |= r.rights; // TODO: Deal with reverse rights
visible = true;
}
r = g.links[nodeid];
if (r != null) {
if (r.rights == 0xFFFFFFFF) { func(nodes[0], 0xFFFFFFFF, true); return; } // User has full rights thru a user group direct link, stop here.
rights |= r.rights; // TODO: Deal with reverse rights
visible = true;
}
}
}
}
// Return the rights we found
func(nodes[0], rights, visible);
});
}
// Returns a list of all meshes that this user has some rights too
obj.GetAllMeshWithRights = function (user, rights) {
if (typeof user == 'string') { user = obj.users[user]; }
if ((user == null) || (user.links == null)) { return []; }
var r = [];
if ((user.siteadmin == 0xFFFFFFFF) && (parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0)) {
// This is a super user that can see all device groups for a given domain
var meshStartStr = 'mesh/' + user.domain + '/';
for (var i in obj.meshes) { if ((obj.meshes[i]._id.startsWith(meshStartStr)) && (obj.meshes[i].deleted == null)) { r.push(obj.meshes[i]); } }
return r;
}
for (var i in user.links) {
if (i.startsWith('mesh/')) {
// Grant access to a device group thru a direct link
const m = obj.meshes[i];
if ((m) && (m.deleted == null) && ((rights == null) || ((m.rights & rights) != 0))) {
if (r.indexOf(m) == -1) { r.push(m); }
}
} else if (i.startsWith('ugrp/')) {
// Grant access to a device group thru a user group
const g = obj.userGroups[i];
if (g && (g.links != null) && ((rights == null) || ((g.rights & rights) != 0))) {
for (var j in g.links) {
if (j.startsWith('mesh/')) {
const m = obj.meshes[j];
if ((m) && (m.deleted == null)) {
if (r.indexOf(m) == -1) { r.push(m); }
}
}
}
}
}
}
return r;
}
// Returns a list of all mesh id's that this user has some rights too
obj.GetAllMeshIdWithRights = function (user, rights) {
if (typeof user == 'string') { user = obj.users[user]; }
if ((user == null) || (user.links == null)) { return []; }
var r = [];
if ((user.siteadmin == 0xFFFFFFFF) && (parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0)) {
// This is a super user that can see all device groups for a given domain
var meshStartStr = 'mesh/' + user.domain + '/';
for (var i in obj.meshes) { if ((obj.meshes[i]._id.startsWith(meshStartStr)) && (obj.meshes[i].deleted == null)) { r.push(obj.meshes[i]._id); } }
return r;
}
for (var i in user.links) {
if (i.startsWith('mesh/')) {
// Grant access to a device group thru a direct link
const m = obj.meshes[i];
if ((m) && (m.deleted == null) && ((rights == null) || ((m.rights & rights) != 0))) {
if (r.indexOf(m._id) == -1) { r.push(m._id); }
}
} else if (i.startsWith('ugrp/')) {
// Grant access to a device group thru a user group
const g = obj.userGroups[i];
if (g && (g.links != null) && ((rights == null) || ((g.rights & rights) != 0))) {
for (var j in g.links) {
if (j.startsWith('mesh/')) {
const m = obj.meshes[j];
if ((m) && (m.deleted == null)) {
if (r.indexOf(m._id) == -1) { r.push(m._id); }
}
}
}
}
}
}
return r;
}
// Get the rights of a user on a given device group
obj.GetMeshRights = function (user, mesh) {
if ((user == null) || (mesh == null)) { return 0; }
if (typeof user == 'string') { user = obj.users[user]; }
if ((user == null) || (user.links == null)) { return 0; }
var r, meshid;
if (typeof mesh == 'string') {
meshid = mesh;
} else if ((typeof mesh == 'object') && (typeof mesh._id == 'string')) {
meshid = mesh._id;
} else return 0;
// Check if this is a super user that can see all device groups for a given domain
if ((user.siteadmin == 0xFFFFFFFF) && (parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0) && (meshid.startsWith('mesh/' + user.domain + '/'))) { return 0xFFFFFFFF; }
// Check direct user to device group permissions
var rights = 0;
r = user.links[meshid];
if (r != null) {
var rights = r.rights;
if (rights == 0xFFFFFFFF) { return rights; } // If the user has full access thru direct link, stop here.
}
// Check if we are part of any user groups that would give this user more access.
for (var i in user.links) {
if (i.startsWith('ugrp')) {
const g = obj.userGroups[i];
if (g) {
r = g.links[meshid];
if (r != null) {
if (r.rights == 0xFFFFFFFF) {
return r.rights; // If the user hash full access thru a user group link, stop here.
} else {
rights |= r.rights; // Add to existing rights (TODO: Deal with reverse rights)
}
}
}
}
}
return rights;
}
// Returns true if the user can view the given device group
obj.IsMeshViewable = function (user, mesh) {
if ((user == null) || (mesh == null)) { return false; }
if (typeof user == 'string') { user = obj.users[user]; }
if ((user == null) || (user.links == null)) { return false; }
var meshid;
if (typeof mesh == 'string') {
meshid = mesh;
} else if ((typeof mesh == 'object') && (typeof mesh._id == 'string')) {
meshid = mesh._id;
} else return false;
// Check if this is a super user that can see all device groups for a given domain
if ((user.siteadmin == 0xFFFFFFFF) && (parent.config.settings.managealldevicegroups.indexOf(user._id) >= 0) && (meshid.startsWith('mesh/' + user.domain + '/'))) { return true; }
// Check direct user to device group permissions
if (user.links[meshid] != null) { return true; } // If the user has a direct link, stop here.
// Check if we are part of any user groups that would give this user visibility to this device group.
for (var i in user.links) {
if (i.startsWith('ugrp')) {
const g = obj.userGroups[i];
if (g && (g.links[meshid] != null)) { return true; } // If the user has a user group link, stop here.
}
}
return false;
}
// Return the user rights for a given node
obj.GetNodeRights = function (user, mesh, nodeid) {
if ((user == null) || (mesh == null) || (nodeid == null)) { return 0; }
if (typeof user == 'string') { user = obj.users[user]; }
var r = obj.GetMeshRights(user, mesh);
if (r == 0xFFFFFFFF) return r;
// Check direct device rights using device data
if ((user.links != null) && (user.links[nodeid] != null)) { r |= user.links[nodeid].rights; } // TODO: Deal with reverse permissions
if (r == 0xFFFFFFFF) return r;
// Check direct device rights thru a user group
for (var i in user.links) {
if (i.startsWith('ugrp')) {
const g = obj.userGroups[i];
if (g && (g.links[nodeid] != null)) { r |= g.links[nodeid].rights; }
}
}
return r;
}
// Returns a list of displatch targets for a given mesh
// We have to target the meshid and all user groups for this mesh, plus any added targets
obj.CreateMeshDispatchTargets = function (mesh, addedTargets) {
var targets = (addedTargets != null) ? addedTargets : [];
if (targets.indexOf('*') == -1) { targets.push('*'); }
if (typeof mesh == 'string') { mesh = obj.meshes[mesh]; }
if (mesh != null) { targets.push(mesh._id); for (var i in mesh.links) { if (i.startsWith('ugrp/')) { targets.push(i); } } }
return targets;
}
// Returns a list of displatch targets for a given mesh
// We have to target the meshid and all user groups for this mesh, plus any added targets
obj.CreateNodeDispatchTargets = function (mesh, nodeid, addedTargets) {
var targets = (addedTargets != null) ? addedTargets : [];
targets.push(nodeid);
if (targets.indexOf('*') == -1) { targets.push('*'); }
if (typeof mesh == 'string') { mesh = obj.meshes[mesh]; }
if (mesh != null) { targets.push(mesh._id); for (var i in mesh.links) { if (i.startsWith('ugrp/')) { targets.push(i); } } }
for (var i in obj.userGroups) { const g = obj.userGroups[i]; if ((g != null) && (g.links != null) && (g.links[nodeid] != null)) { targets.push(i); } }
return targets;
}
// Clone a safe version of a user object, remove everything that is secret.
obj.CloneSafeUser = function (user) {
if (typeof user != 'object') { return user; }
var user2 = Object.assign({}, user); // Shallow clone
delete user2.hash;
delete user2.passhint;
delete user2.salt;
delete user2.type;
delete user2.domain;
delete user2.subscriptions;
delete user2.passtype;
delete user2.otpsms;
if ((typeof user2.otpekey == 'object') && (user2.otpekey != null)) { user2.otpekey = 1; } // Indicates that email 2FA is enabled.
if ((typeof user2.otpsecret == 'string') && (user2.otpsecret != null)) { user2.otpsecret = 1; } // Indicates a time secret is present.
if ((typeof user2.otpkeys == 'object') && (user2.otpkeys != null)) { user2.otpkeys = 0; if (user.otpkeys != null) { for (var i = 0; i < user.otpkeys.keys.length; i++) { if (user.otpkeys.keys[i].u == true) { user2.otpkeys = 1; } } } } // Indicates the number of one time backup codes that are active.
if ((typeof user2.otphkeys == 'object') && (user2.otphkeys != null)) { user2.otphkeys = user2.otphkeys.length; } // Indicates the number of hardware keys setup
return user2;
}
// Clone a safe version of a node object, remove everything that is secret.
obj.CloneSafeNode = function (node) {
if (typeof node != 'object') { return node; }
var r = node;
if (r.intelamt && r.intelamt.pass) {
r = Object.assign({}, r); // Shallow clone
r.intelamt = Object.assign({}, r.intelamt); // Shallow clone
delete r.intelamt.pass; // Remove the Intel AMT password from the node
}
return r;
}
// Clone a safe version of a mesh object, remove everything that is secret.
obj.CloneSafeMesh = function (mesh) {
if (typeof mesh != 'object') { return mesh; }
var r = mesh;
if (r.amt && r.amt.password) {
r = Object.assign({}, r); // Shallow clone
r.amt = Object.assign({}, r.amt); // Shallow clone
delete r.amt.password; // Remove the Intel AMT password from the policy
}
return r;
}
// Filter the user web site and only output state that we need to keep
const acceptableUserWebStateStrings = ['webPageStackMenu', 'notifications', 'deviceView', 'nightMode', 'webPageFullScreen', 'search', 'showRealNames', 'sort', 'deskAspectRatio', 'viewsize', 'DeskControl', 'uiMode', 'footerBar'];
const acceptableUserWebStateDesktopStrings = ['encoding', 'showfocus', 'showmouse', 'showcad', 'limitFrameRate', 'noMouseRotate', 'quality', 'scaling']
obj.filterUserWebState = function (state) {
if (typeof state == 'string') { try { state = JSON.parse(state); } catch (ex) { return null; } }
if ((state == null) || (typeof state != 'object')) { return null; }
var out = {};
for (var i in acceptableUserWebStateStrings) {
var n = acceptableUserWebStateStrings[i];
if ((state[n] != null) && ((typeof state[n] == 'number') || (typeof state[n] == 'boolean') || ((typeof state[n] == 'string') && (state[n].length < 64)))) { out[n] = state[n]; }
}
if ((typeof state.stars == 'string') && (state.stars.length < 2048)) { out.stars = state.stars; }
if (typeof state.desktopsettings == 'string') { try { state.desktopsettings = JSON.parse(state.desktopsettings); } catch (ex) { delete state.desktopsettings; } }
if (state.desktopsettings != null) {
out.desktopsettings = {};
for (var i in acceptableUserWebStateDesktopStrings) {
var n = acceptableUserWebStateDesktopStrings[i];
if ((state.desktopsettings[n] != null) && ((typeof state.desktopsettings[n] == 'number') || (typeof state.desktopsettings[n] == 'boolean') || ((typeof state.desktopsettings[n] == 'string') && (state.desktopsettings[n].length < 32)))) { out.desktopsettings[n] = state.desktopsettings[n]; }
}
out.desktopsettings = JSON.stringify(out.desktopsettings);
}
return JSON.stringify(out);
}
// Return the correct render page given mobile, minify and override path.
function getRenderPage(pagename, req, domain) {
var mobile = isMobileBrowser(req), minify = (domain.minify == true), p;
if (req.query.mobile == '1') { mobile = true; } else if (req.query.mobile == '0') { mobile = false; }
if (req.query.minify == '1') { minify = true; } else if (req.query.minify == '0') { minify = false; }
if (mobile) {
if ((domain != null) && (domain.webviewspath != null)) { // If the domain has a web views path, use that first
if (minify) {
p = obj.path.join(domain.webviewspath, pagename + '-mobile-min');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Mobile + Minify + Override document
}
p = obj.path.join(domain.webviewspath, pagename + '-mobile');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Mobile + Override document
}
if (obj.parent.webViewsOverridePath != null) {
if (minify) {
p = obj.path.join(obj.parent.webViewsOverridePath, pagename + '-mobile-min');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Mobile + Minify + Override document
}
p = obj.path.join(obj.parent.webViewsOverridePath, pagename + '-mobile');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Mobile + Override document
}
if (minify) {
p = obj.path.join(obj.parent.webViewsPath, pagename + '-mobile-min');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Mobile + Minify document
}
p = obj.path.join(obj.parent.webViewsPath, pagename + '-mobile');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Mobile document
}
if ((domain != null) && (domain.webviewspath != null)) { // If the domain has a web views path, use that first
if (minify) {
p = obj.path.join(domain.webviewspath, pagename + '-min');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Minify + Override document
}
p = obj.path.join(domain.webviewspath, pagename);
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Override document
}
if (obj.parent.webViewsOverridePath != null) {
if (minify) {
p = obj.path.join(obj.parent.webViewsOverridePath, pagename + '-min');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Minify + Override document
}
p = obj.path.join(obj.parent.webViewsOverridePath, pagename);
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Override document
}
if (minify) {
p = obj.path.join(obj.parent.webViewsPath, pagename + '-min');
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Minify document
}
p = obj.path.join(obj.parent.webViewsPath, pagename);
if (obj.fs.existsSync(p + '.handlebars')) { return p; } // Default document
return null;
}
// Return the correct render page arguments.
function getRenderArgs(xargs, req, domain) {
var minify = (domain.minify == true);
if (req.query.minify == '1') { minify = true; } else if (req.query.minify == '0') { minify = false; }
xargs.min = minify ? '-min' : '';
xargs.titlehtml = domain.titlehtml;
xargs.title = (domain.title != null) ? domain.title : 'MeshCentral';
if ((domain.titlepicture == null) && (domain.titlehtml == null)) {
if (domain.title == null) {
xargs.title1 = 'MeshCentral';
xargs.title2 = '';
} else {
xargs.title1 = domain.title;
xargs.title2 = domain.title2 ? domain.title2 : '';
}
} else {
xargs.title1 = domain.title1 ? domain.title1 : '';
xargs.title2 = (domain.title1 && domain.title2) ? domain.title2 : '';
}
xargs.extitle = encodeURIComponent(xargs.title);
xargs.domainurl = domain.url;
if (typeof domain.hide == 'number') { xargs.hide = domain.hide; }
return xargs;
}
// Route a command from a agent. domainid, nodeid and meshid are the values of the source agent.
obj.routeAgentCommand = function (command, domainid, nodeid, meshid) {
// Route a message.
// If this command has a sessionid, that is the target.
if (command.sessionid != null) {
if (typeof command.sessionid != 'string') return;
var splitsessionid = command.sessionid.split('/');
// Check that we are in the same domain and the user has rights over this node.
if ((splitsessionid.length == 4) && (splitsessionid[0] == 'user') && (splitsessionid[1] == domainid)) {
// Check if this user has rights to get this message
if (obj.GetNodeRights(splitsessionid[0] + '/' + splitsessionid[1] + '/' + splitsessionid[2], meshid, nodeid) == 0) return; // TODO: Check if this is ok
// See if the session is connected. If so, go ahead and send this message to the target node
var ws = obj.wssessions2[command.sessionid];
if (ws != null) {
command.nodeid = nodeid; // Set the nodeid, required for responses.
delete command.sessionid; // Remove the sessionid, since we are sending to that sessionid, so it's implyed.
try { ws.send(JSON.stringify(command)); } catch (ex) { }
} else if (parent.multiServer != null) {
// See if we can send this to a peer server
var serverid = obj.wsPeerSessions2[command.sessionid];
if (serverid != null) {
command.fromNodeid = nodeid;
parent.multiServer.DispatchMessageSingleServer(command, serverid);
}
}
}
} else if (command.userid != null) { // If this command has a userid, that is the target.
if (typeof command.userid != 'string') return;
var splituserid = command.userid.split('/');
// Check that we are in the same domain and the user has rights over this node.
if ((splituserid[0] == 'user') && (splituserid[1] == domainid)) {
// Check if this user has rights to get this message
if (obj.GetNodeRights(command.userid, meshid, nodeid) == 0) return; // TODO: Check if this is ok
// See if the session is connected
var sessions = obj.wssessions[command.userid];
// Go ahead and send this message to the target node
if (sessions != null) {
command.nodeid = nodeid; // Set the nodeid, required for responses.
delete command.userid; // Remove the userid, since we are sending to that userid, so it's implyed.
for (i in sessions) { sessions[i].send(JSON.stringify(command)); }
}
if (parent.multiServer != null) {
// TODO: Add multi-server support
}
}
} else { // Route this command to all users with MESHRIGHT_AGENTCONSOLE rights to this device group
command.nodeid = nodeid;
var cmdstr = JSON.stringify(command);
// Find all connected user sessions with access to this device
for (var userid in obj.wssessions) {
var xsessions = obj.wssessions[userid];
if (obj.GetNodeRights(userid, meshid, nodeid) != 0) {
// Send the message to all sessions for this user on this server
for (i in xsessions) { try { xsessions[i].send(cmdstr); } catch (e) { } }
}
}
// Send the message to all users of other servers
if (parent.multiServer != null) {
delete command.nodeid;
command.fromNodeid = nodeid;
command.meshid = meshid;
parent.multiServer.DispatchMessage(command);
}
}
}
// Returns a list of acceptable languages in order
obj.getLanguageCodes = function (req) {
// If a user set a localization, use that
if ((req.query.lang == null) && (req.session != null) && (req.session.userid)) {
var user = obj.users[req.session.userid];
if ((user != null) && (user.lang != null)) { req.query.lang = user.lang; }
};
// Get a list of acceptable languages in order
var acceptLanguages = [];
if (req.query.lang != null) {
acceptLanguages.push(req.query.lang.toLowerCase());
} else {
if (req.headers['accept-language'] != null) {
var acceptLanguageSplit = req.headers['accept-language'].split(';');
for (var i in acceptLanguageSplit) {
var acceptLanguageSplitEx = acceptLanguageSplit[i].split(',');
for (var j in acceptLanguageSplitEx) { if (acceptLanguageSplitEx[j].startsWith('q=') == false) { acceptLanguages.push(acceptLanguageSplitEx[j].toLowerCase()); } }
}
}
}
return acceptLanguages;
}
// Render a page using the proper language
function render(req, res, filename, args) {
if (obj.renderPages != null) {
// Get the list of acceptable languages in order
var acceptLanguages = obj.getLanguageCodes(req);
// Take a look at the options we have for this file
var fileOptions = obj.renderPages[obj.path.basename(filename)];
if (fileOptions != null) {
for (var i in acceptLanguages) {
if ((acceptLanguages[i] == 'en') || (acceptLanguages[i].startsWith('en-'))) { args.lang = 'en'; break; } // English requested, break out.
if (fileOptions[acceptLanguages[i]] != null) {
// Found a match. If the file no longer exists, default to English.
obj.fs.exists(fileOptions[acceptLanguages[i]] + '.handlebars', function (exists) {
if (exists) { args.lang = acceptLanguages[i]; res.render(fileOptions[acceptLanguages[i]], args); } else { args.lang = 'en'; res.render(filename, args); }
});
return;
}
}
}
}
// No matches found, render the default english page.
res.render(filename, args);
}
// Get the list of pages with different languages that can be rendered
function getRenderList() {
// Fetch default rendeing pages
var translateFolder = null;
if (obj.fs.existsSync('views/translations')) { translateFolder = 'views/translations'; }
if (obj.fs.existsSync(obj.path.join(__dirname, 'views', 'translations'))) { translateFolder = obj.path.join(__dirname, 'views', 'translations'); }
if (translateFolder != null) {
obj.renderPages = {};
obj.renderLanguages = ['en'];
var files = obj.fs.readdirSync(translateFolder);
for (var i in files) {
var name = files[i];
if (name.endsWith('.handlebars')) {
name = name.substring(0, name.length - 11);
var xname = name.split('_');
if (xname.length == 2) {
if (obj.renderPages[xname[0]] == null) { obj.renderPages[xname[0]] = {}; }
obj.renderPages[xname[0]][xname[1]] = obj.path.join(translateFolder, name);
if (obj.renderLanguages.indexOf(xname[1]) == -1) { obj.renderLanguages.push(xname[1]); }
}
}
}
// See if there are any custom rending pages that will override the default ones
if ((obj.parent.webViewsOverridePath != null) && (obj.fs.existsSync(obj.path.join(obj.parent.webViewsOverridePath, 'translations')))) {
translateFolder = obj.path.join(obj.parent.webViewsOverridePath, 'translations');
var files = obj.fs.readdirSync(translateFolder);
for (var i in files) {
var name = files[i];
if (name.endsWith('.handlebars')) {
name = name.substring(0, name.length - 11);
var xname = name.split('_');
if (xname.length == 2) {
if (obj.renderPages[xname[0]] == null) { obj.renderPages[xname[0]] = {}; }
obj.renderPages[xname[0]][xname[1]] = obj.path.join(translateFolder, name);
if (obj.renderLanguages.indexOf(xname[1]) == -1) { obj.renderLanguages.push(xname[1]); }
}
}
}
}
}
}
// Get the list of pages with different languages that can be rendered
function getEmailLanguageList() {
// Fetch default rendeing pages
var translateFolder = null;
if (obj.fs.existsSync('emails/translations')) { translateFolder = 'emails/translations'; }
if (obj.fs.existsSync(obj.path.join(__dirname, 'emails', 'translations'))) { translateFolder = obj.path.join(__dirname, 'emails', 'translations'); }
if (translateFolder != null) {
obj.emailLanguages = ['en'];
var files = obj.fs.readdirSync(translateFolder);
for (var i in files) {
var name = files[i];
if (name.endsWith('.html')) {
name = name.substring(0, name.length - 5);
var xname = name.split('_');
if (xname.length == 2) {
if (obj.emailLanguages.indexOf(xname[1]) == -1) { obj.emailLanguages.push(xname[1]); }
}
}
}
// See if there are any custom rending pages that will override the default ones
if ((obj.parent.webEmailsOverridePath != null) && (obj.fs.existsSync(obj.path.join(obj.parent.webEmailsOverridePath, 'translations')))) {
translateFolder = obj.path.join(obj.parent.webEmailsOverridePath, 'translations');
var files = obj.fs.readdirSync(translateFolder);
for (var i in files) {
var name = files[i];
if (name.endsWith('.html')) {
name = name.substring(0, name.length - 5);
var xname = name.split('_');
if (xname.length == 2) {
if (obj.emailLanguages.indexOf(xname[1]) == -1) { obj.emailLanguages.push(xname[1]); }
}
}
}
}
}
}
// Return true if a mobile browser is detected.
// This code comes from "http://detectmobilebrowsers.com/" and was modified, This is free and unencumbered software released into the public domain. For more information, please refer to the http://unlicense.org/
function isMobileBrowser(req) {
//var ua = req.headers['user-agent'].toLowerCase();
//return (/(android|bb\d+|meego).+mobile|mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(ua) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(ua.substr(0, 4)));
if (typeof req.headers['user-agent'] != 'string') return false;
return (req.headers['user-agent'].toLowerCase().indexOf('mobile') >= 0);
}
// Return the query string portion of the URL, the ? and anything after.
function getQueryPortion(req) { var s = req.url.indexOf('?'); if (s == -1) { if (req.body && req.body.urlargs) { return req.body.urlargs; } return ''; } return req.url.substring(s); }
// Generate a random Intel AMT password
function checkAmtPassword(p) { return (p.length > 7) && (/\d/.test(p)) && (/[a-z]/.test(p)) && (/[A-Z]/.test(p)) && (/\W/.test(p)); }
function getRandomAmtPassword() { var p; do { p = Buffer.from(obj.crypto.randomBytes(9), 'binary').toString('base64').split('/').join('@'); } while (checkAmtPassword(p) == false); return p; }
function getRandomPassword() { return Buffer.from(obj.crypto.randomBytes(9), 'binary').toString('base64').split('/').join('@'); }
function getRandomLowerCase(len) { var r = '', random = obj.crypto.randomBytes(len); for (var i = 0; i < len; i++) { r += String.fromCharCode(97 + (random[i] % 26)); } return r; }
// Generate a 8 digit integer with even random probability for each value.
function getRandomEightDigitInteger() { var bigInt; do { bigInt = parent.crypto.randomBytes(4).readUInt32BE(0); } while (bigInt >= 4200000000); return bigInt % 100000000; }
function getRandomSixDigitInteger() { var bigInt; do { bigInt = parent.crypto.randomBytes(4).readUInt32BE(0); } while (bigInt >= 4200000000); return bigInt % 1000000; }
// Clean a IPv6 address that encodes a IPv4 address
function cleanRemoteAddr(addr) { if (typeof addr != 'string') { return null; } if (addr.indexOf('::ffff:') == 0) { return addr.substring(7); } else { return addr; } }
// Record a new entry in a recording log
function recordingEntry(fd, type, flags, data, func, tag) {
try {
if (typeof data == 'string') {
// String write
var blockData = Buffer.from(data), header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
header.writeInt16BE(type, 0); // Type (1 = Header, 2 = Network Data)
header.writeInt16BE(flags, 2); // Flags (1 = Binary, 2 = User)
header.writeInt32BE(blockData.length, 4); // Size
header.writeIntBE(new Date(), 10, 6); // Time
var block = Buffer.concat([header, blockData]);
obj.fs.write(fd, block, 0, block.length, function () { func(fd, tag); });
} else {
// Binary write
var header = Buffer.alloc(16); // Header: Type (2) + Flags (2) + Size(4) + Time(8)
header.writeInt16BE(type, 0); // Type (1 = Header, 2 = Network Data)
header.writeInt16BE(flags | 1, 2); // Flags (1 = Binary, 2 = User)
header.writeInt32BE(data.length, 4); // Size
header.writeIntBE(new Date(), 10, 6); // Time
var block = Buffer.concat([header, data]);
obj.fs.write(fd, block, 0, block.length, function () { func(fd, tag); });
}
} catch (ex) { console.log(ex); func(fd, tag); }
}
// This is the invalid login throttling code
obj.badLoginTable = {};
obj.badLoginTableLastClean = 0;
if (parent.config.settings == null) { parent.config.settings = {}; }
if (parent.config.settings.maxinvalidlogin !== false) {
if (typeof parent.config.settings.maxinvalidlogin != 'object') { parent.config.settings.maxinvalidlogin = { time: 10, count: 10 }; }
if (typeof parent.config.settings.maxinvalidlogin.time != 'number') { parent.config.settings.maxinvalidlogin.time = 10; }
if (typeof parent.config.settings.maxinvalidlogin.count != 'number') { parent.config.settings.maxinvalidlogin.count = 10; }
if ((typeof parent.config.settings.maxinvalidlogin.coolofftime != 'number') || (parent.config.settings.maxinvalidlogin.coolofftime < 1)) { parent.config.settings.maxinvalidlogin.coolofftime = null; }
}
obj.setbadLogin = function (ip) { // Set an IP address that just did a bad login request
if (parent.config.settings.maxinvalidlogin === false) return;
if (typeof ip == 'object') { ip = ip.clientIp; }
var splitip = ip.split('.');
if (splitip.length == 4) { ip = (splitip[0] + '.' + splitip[1] + '.' + splitip[2] + '.*'); }
if (++obj.badLoginTableLastClean > 100) { obj.cleanBadLoginTable(); }
if (typeof obj.badLoginTable[ip] == 'number') { if (obj.badLoginTable[ip] < Date.now()) { delete obj.badLoginTable[ip]; } else { return; } } // Check cooloff period
if (obj.badLoginTable[ip] == null) { obj.badLoginTable[ip] = [Date.now()]; } else { obj.badLoginTable[ip].push(Date.now()); }
if ((obj.badLoginTable[ip].length >= parent.config.settings.maxinvalidlogin.count) && (parent.config.settings.maxinvalidlogin.coolofftime != null)) {
obj.badLoginTable[ip] = Date.now() + (parent.config.settings.maxinvalidlogin.coolofftime * 60000); // Move to cooloff period
}
}
obj.checkAllowLogin = function (ip) { // Check if an IP address is allowed to login
if (parent.config.settings.maxinvalidlogin === false) return true;
if (typeof ip == 'object') { ip = ip.clientIp; }
var splitip = ip.split('.');
if (splitip.length == 4) { ip = (splitip[0] + '.' + splitip[1] + '.' + splitip[2] + '.*'); } // If this is IPv4, keep only the 3 first
var cutoffTime = Date.now() - (parent.config.settings.maxinvalidlogin.time * 60000); // Time in minutes
var ipTable = obj.badLoginTable[ip];
if (ipTable == null) return true;
if (typeof ipTable == 'number') { if (obj.badLoginTable[ip] < Date.now()) { delete obj.badLoginTable[ip]; } else { return false; } } // Check cooloff period
while ((ipTable.length > 0) && (ipTable[0] < cutoffTime)) { ipTable.shift(); }
if (ipTable.length == 0) { delete obj.badLoginTable[ip]; return true; }
return (ipTable.length < parent.config.settings.maxinvalidlogin.count); // No more than x bad logins in x minutes
}
obj.cleanBadLoginTable = function () { // Clean up the IP address login blockage table, we do this occasionaly.
if (parent.config.settings.maxinvalidlogin === false) return;
var cutoffTime = Date.now() - (parent.config.settings.maxinvalidlogin.time * 60000); // Time in minutes
for (var ip in obj.badLoginTable) {
var ipTable = obj.badLoginTable[ip];
if (typeof ipTable == 'number') {
if (obj.badLoginTable[ip] < Date.now()) { delete obj.badLoginTable[ip]; } // Check cooloff period
} else {
while ((ipTable.length > 0) && (ipTable[0] < cutoffTime)) { ipTable.shift(); }
if (ipTable.length == 0) { delete obj.badLoginTable[ip]; }
}
}
obj.badLoginTableLastClean = 0;
}
return obj;
};
|
"""
Standard container-class for easy multiple-inheritance.
Try to inherit from the ndarray instead of using this class as this is not
complete.
"""
from __future__ import division, absolute_import, print_function
from numpy.core import (
array, asarray, absolute, add, subtract, multiply, divide,
remainder, power, left_shift, right_shift, bitwise_and, bitwise_or,
bitwise_xor, invert, less, less_equal, not_equal, equal, greater,
greater_equal, shape, reshape, arange, sin, sqrt, transpose
)
from numpy.compat import long
class container(object):
def __init__(self, data, dtype=None, copy=True):
self.array = array(data, dtype, copy=copy)
def __repr__(self):
if len(self.shape) > 0:
return self.__class__.__name__ + repr(self.array)[len("array"):]
else:
return self.__class__.__name__ + "(" + repr(self.array) + ")"
def __array__(self, t=None):
if t:
return self.array.astype(t)
return self.array
# Array as sequence
def __len__(self):
return len(self.array)
def __getitem__(self, index):
return self._rc(self.array[index])
def __getslice__(self, i, j):
return self._rc(self.array[i:j])
def __setitem__(self, index, value):
self.array[index] = asarray(value, self.dtype)
def __setslice__(self, i, j, value):
self.array[i:j] = asarray(value, self.dtype)
def __abs__(self):
return self._rc(absolute(self.array))
def __neg__(self):
return self._rc(-self.array)
def __add__(self, other):
return self._rc(self.array + asarray(other))
__radd__ = __add__
def __iadd__(self, other):
add(self.array, other, self.array)
return self
def __sub__(self, other):
return self._rc(self.array - asarray(other))
def __rsub__(self, other):
return self._rc(asarray(other) - self.array)
def __isub__(self, other):
subtract(self.array, other, self.array)
return self
def __mul__(self, other):
return self._rc(multiply(self.array, asarray(other)))
__rmul__ = __mul__
def __imul__(self, other):
multiply(self.array, other, self.array)
return self
def __div__(self, other):
return self._rc(divide(self.array, asarray(other)))
def __rdiv__(self, other):
return self._rc(divide(asarray(other), self.array))
def __idiv__(self, other):
divide(self.array, other, self.array)
return self
def __mod__(self, other):
return self._rc(remainder(self.array, other))
def __rmod__(self, other):
return self._rc(remainder(other, self.array))
def __imod__(self, other):
remainder(self.array, other, self.array)
return self
def __divmod__(self, other):
return (self._rc(divide(self.array, other)),
self._rc(remainder(self.array, other)))
def __rdivmod__(self, other):
return (self._rc(divide(other, self.array)),
self._rc(remainder(other, self.array)))
def __pow__(self, other):
return self._rc(power(self.array, asarray(other)))
def __rpow__(self, other):
return self._rc(power(asarray(other), self.array))
def __ipow__(self, other):
power(self.array, other, self.array)
return self
def __lshift__(self, other):
return self._rc(left_shift(self.array, other))
def __rshift__(self, other):
return self._rc(right_shift(self.array, other))
def __rlshift__(self, other):
return self._rc(left_shift(other, self.array))
def __rrshift__(self, other):
return self._rc(right_shift(other, self.array))
def __ilshift__(self, other):
left_shift(self.array, other, self.array)
return self
def __irshift__(self, other):
right_shift(self.array, other, self.array)
return self
def __and__(self, other):
return self._rc(bitwise_and(self.array, other))
def __rand__(self, other):
return self._rc(bitwise_and(other, self.array))
def __iand__(self, other):
bitwise_and(self.array, other, self.array)
return self
def __xor__(self, other):
return self._rc(bitwise_xor(self.array, other))
def __rxor__(self, other):
return self._rc(bitwise_xor(other, self.array))
def __ixor__(self, other):
bitwise_xor(self.array, other, self.array)
return self
def __or__(self, other):
return self._rc(bitwise_or(self.array, other))
def __ror__(self, other):
return self._rc(bitwise_or(other, self.array))
def __ior__(self, other):
bitwise_or(self.array, other, self.array)
return self
def __pos__(self):
return self._rc(self.array)
def __invert__(self):
return self._rc(invert(self.array))
def _scalarfunc(self, func):
if len(self.shape) == 0:
return func(self[0])
else:
raise TypeError(
"only rank-0 arrays can be converted to Python scalars.")
def __complex__(self):
return self._scalarfunc(complex)
def __float__(self):
return self._scalarfunc(float)
def __int__(self):
return self._scalarfunc(int)
def __long__(self):
return self._scalarfunc(long)
def __hex__(self):
return self._scalarfunc(hex)
def __oct__(self):
return self._scalarfunc(oct)
def __lt__(self, other):
return self._rc(less(self.array, other))
def __le__(self, other):
return self._rc(less_equal(self.array, other))
def __eq__(self, other):
return self._rc(equal(self.array, other))
def __ne__(self, other):
return self._rc(not_equal(self.array, other))
def __gt__(self, other):
return self._rc(greater(self.array, other))
def __ge__(self, other):
return self._rc(greater_equal(self.array, other))
def copy(self):
return self._rc(self.array.copy())
def tostring(self):
return self.array.tostring()
def byteswap(self):
return self._rc(self.array.byteswap())
def astype(self, typecode):
return self._rc(self.array.astype(typecode))
def _rc(self, a):
if len(shape(a)) == 0:
return a
else:
return self.__class__(a)
def __array_wrap__(self, *args):
return self.__class__(args[0])
def __setattr__(self, attr, value):
if attr == 'array':
object.__setattr__(self, attr, value)
return
try:
self.array.__setattr__(attr, value)
except AttributeError:
object.__setattr__(self, attr, value)
# Only called after other approaches fail.
def __getattr__(self, attr):
if (attr == 'array'):
return object.__getattribute__(self, attr)
return self.array.__getattribute__(attr)
#############################################################
# Test of class container
#############################################################
if __name__ == '__main__':
temp = reshape(arange(10000), (100, 100))
ua = container(temp)
# new object created begin test
print(dir(ua))
print(shape(ua), ua.shape) # I have changed Numeric.py
ua_small = ua[:3, :5]
print(ua_small)
# this did not change ua[0,0], which is not normal behavior
ua_small[0, 0] = 10
print(ua_small[0, 0], ua[0, 0])
print(sin(ua_small) / 3. * 6. + sqrt(ua_small ** 2))
print(less(ua_small, 103), type(less(ua_small, 103)))
print(type(ua_small * reshape(arange(15), shape(ua_small))))
print(reshape(ua_small, (5, 3)))
print(transpose(ua_small))
|
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = "";
let currentLine = 0;
process.stdin.on("data", inputStdin => {
inputString += inputStdin;
});
process.stdin.on("end", _ => {
inputString = inputString
.replace(/\s*$/, "")
.split("\n")
.map(str => str.replace(/\s*$/, ""));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const n = parseInt(readLine(), 10);
const arr = readLine()
.split(" ")
.map(arrTemp => parseInt(arrTemp, 10));
for (let i = n - 1; i > -1; i--) {
process.stdout.write(`${arr[i]} `);
}
}
|
"""
Genomic SNP endpoint.
This endpoint is specific for querying SNPs, hence the parameters accepted by the request
differ from the ones in the basic query endpoint.
.. note:: See ``schemas/genomic_snp.json`` for checking the parameters accepted in this endpoint.
"""
import ast
import logging
from .exceptions import BeaconBadRequest, BeaconServerError, BeaconForbidden, BeaconUnauthorised
from .. import __apiVersion__, __id__
from ..conf.config import DB_SCHEMA
from ..utils.polyvalent_functions import create_prepstmt_variables, filter_exists, datasetHandover
from ..utils.polyvalent_functions import prepare_filter_parameter, parse_filters_request
from ..utils.polyvalent_functions import fetch_datasets_access, access_resolution
from ..utils.polyvalent_functions import filter_response, snp_resultsHandover, fetch_variantAnnotations
from .access_levels import ACCESS_LEVELS_DICT
from ..utils.translate2accesslevels import snp2access
from ..utils.models import variant_object, variantAnnotation_object
LOG = logging.getLogger(__name__)
# ----------------------------------------------------------------------------------------------------------------------
# FORMATTING
# ----------------------------------------------------------------------------------------------------------------------
def create_variantsFound(processed_request, datasets, variant_id, variant_annotations):
"""
Format the response inside a variantsFound object that will be a list containing ONLY one item
(similar to genomic_region's same named function)
"""
variantsFound = [
{
"variant": variant_object(processed_request, processed_request, variantId = variant_id), # we repeat processed_request beacause in the SNP case, in the second parameter it represents the variant_details
"variantAnnotations": variant_annotations,
"variantHandover": snp_resultsHandover(variant_id) if variant_id else '',
"datasetAlleleResponses": datasets
}
]
return variantsFound
async def transform_record(db_pool, record):
"""Format the record we got from the database to adhere to the response schema."""
# Before creating the dict, we want to get the stable_id from the DB
async with db_pool.acquire(timeout=180) as connection:
try:
query = f"""SELECT stable_id, access_type
FROM beacon_dataset
WHERE id={dict(record).pop("dataset_id")};
"""
statement = await connection.prepare(query)
extra_record = await statement.fetchrow()
except Exception as e:
raise BeaconServerError(f'Query metadata (stableID) DB error: {e}')
response = dict(record)
for dispensable in ["id", "variant_composite_id", "chromosome", "reference", "alternate", "start", "end", "variant_type"]:
response.pop(dispensable)
dataset_name = dict(extra_record).pop("stable_id")
response["datasetId"] = dataset_name
response["internalId"] = response.pop("dataset_id")
response["exists"] = True
response["variantCount"] = response.pop("variant_cnt")
response["callCount"] = response.pop("call_cnt")
response["sampleCount"] = response.pop("sample_cnt")
response["frequency"] = 0 if response.get("frequency") is None else float(response.pop("frequency"))
response["numVariants"] = 0 if response.get("num_variants") is None else response.pop("num_variants")
response["info"] = {"accessType": dict(extra_record).pop("access_type"),
"matchingSampleCount": 0 if response.get("matching_sample_cnt") is None else response.pop("matching_sample_cnt")}
response["datasetHandover"] = datasetHandover(dataset_name)
response["variantId"] = None if response.get("variant_id") == "." else response.pop("variant_id")
return response
def transform_misses(record):
"""Format the missed datasets record we got from the database to adhere to the response schema."""
response = {}
dataset_name = dict(record).get("stableId")
response["datasetId"] = dataset_name
response["internalId"] = dict(record).get("datasetId")
response["exists"] = False
# response["datasetId"] = ''
response["variantCount"] = 0
response["callCount"] = 0
response["sampleCount"] = 0
response["frequency"] = 0
response["numVariants"] = 0
response["info"] = {"accessType": dict(record).get("accessType"),
"matchingSampleCount": 0 if record.get("matching_sample_cnt") is None else record.get("matching_sample_cnt")}
response["datasetHandover"] = datasetHandover(dataset_name)
response["variantId"] = None if record.get("variant_id") == "." else record.get("variant_id")
return response
# ----------------------------------------------------------------------------------------------------------------------
# MAIN QUERY TO THE DATABASE
# ----------------------------------------------------------------------------------------------------------------------
async def fetch_resulting_datasets(db_pool, query_parameters, misses=False, accessible_missing=None):
"""
Contact the DB to fetch the information about the datasets.
:misses: set to True for retrieving data about datasets without the queried variant
:accessible_missing: list of accessible datasets without the variant.
Returns list of datasets dictionaries.
"""
async with db_pool.acquire(timeout=180) as connection:
datasets = []
try:
if misses:
if accessible_missing:
query = f"""SELECT id as "datasetId", access_type as "accessType", stable_id as "stableId"
FROM beacon_dataset
WHERE id IN ({create_prepstmt_variables(len(accessible_missing))});
"""
# LOG.debug(f"QUERY to fetch accessible missing info: {query}")
statement = await connection.prepare(query)
db_response = await statement.fetch(*accessible_missing)
else:
return []
else:
query = f"""SELECT * FROM {DB_SCHEMA}.query_data_response({create_prepstmt_variables(13)});"""
LOG.debug(f"QUERY to fetch hits: {query}")
statement = await connection.prepare(query)
db_response = await statement.fetch(*query_parameters)
for record in list(db_response):
processed = transform_misses(record) if misses else await transform_record(db_pool, record)
datasets.append(processed)
return datasets
except Exception as e:
raise BeaconServerError(f'Query resulting datasets DB error: {e}')
async def get_datasets(db_pool, query_parameters, include_dataset):
"""
Find datasets based on query parameters.
"""
hit_datasets = []
miss_datasets = []
response = []
dataset_ids = query_parameters[-2]
hit_datasets = await fetch_resulting_datasets(db_pool, query_parameters)
LOG.debug(f"hit_datasets: {hit_datasets}")
if include_dataset in ['ALL', 'MISS']:
list_all = list(map(int, dataset_ids.split(",")))
LOG.debug(f"list_all: {list_all}")
list_hits = [dict["internalId"] for dict in hit_datasets]
LOG.debug(f"list_hits: {list_hits}")
accessible_missing = [int(x) for x in list_all if x not in list_hits]
LOG.debug(f"accessible_missing: {accessible_missing}")
miss_datasets = await fetch_resulting_datasets(db_pool, query_parameters, misses=True, accessible_missing=accessible_missing)
response = hit_datasets + miss_datasets
return response
# ----------------------------------------------------------------------------------------------------------------------
# HANDLER FUNCTION
# ----------------------------------------------------------------------------------------------------------------------
async def snp_request_handler(db_pool, processed_request, request):
"""
Construct the Query response.
Process and prepare the parameters, fetch dataset access information, execute
main queries and prepare the response object.
"""
# First we parse the query to prepare it to be used in the SQL function
# We create a list of the parameters that the SQL function needs
correct_parameters = [
"variantType",
"start",
"startMin",
"startMax",
"end",
"endMin",
"endMax",
"referenceName",
"referenceBases",
"alternateBases",
"assemblyId",
"datasetIds",
"filters"]
int_params = ['start', 'end', 'endMax', 'endMin', 'startMax', 'startMin']
query_parameters = []
# Iterate correct_parameters to create the query_parameters list from the processed_request
# in the requiered order and with the right types
for param in correct_parameters:
query_param = processed_request.get(param)
if query_param:
if param in int_params:
query_parameters.append(int(query_param))
else:
query_parameters.append(str(query_param))
else:
if param in int_params:
query_parameters.append(None)
else:
query_parameters.append("null")
# At this point we have a list with the needed parameters called query_parameters, the only thing
# laking is to update the datasetsIds (it can be "null" or processed_request.get("datasetIds"))
LOG.debug(f"Correct param: {correct_parameters}")
LOG.debug(f"Query param: {query_parameters}")
LOG.debug(f"Query param types: {[type(x) for x in query_parameters]}")
# We want to get a list of the datasets available in the database separated in three lists
# depending on the access level (we check all of them if the user hasn't specified anything, if some
# there were given, those are the only ones that are checked)
public_datasets, registered_datasets, controlled_datasets = await fetch_datasets_access(db_pool, query_parameters[-2])
##### TEST CODE TO USE WHEN AAI is integrated
# access_type, accessible_datasets = access_resolution(request, request['token'], request.host, public_datasets,
# registered_datasets, controlled_datasets)
# LOG.info(f"The user has this types of acces: {access_type}")
# query_parameters[-2] = ",".join([str(id) for id in accessible_datasets])
##### END TEST
# NOTE that rigth now we will just focus on the PUBLIC ones to easen the process, so we get all their
# ids and add them to the query
query_parameters[-2] = ",".join([str(id) for id in public_datasets])
# We adapt the filters parameter to be able to use it in the SQL function (e.g. '(technology)::jsonb ?& array[''Illumina Genome Analyzer II'', ''Illumina HiSeq 2000'']')
if query_parameters[-1] != "null":
filters_request_list = ast.literal_eval(query_parameters[-1])
processed_filters_param, _ = await prepare_filter_parameter(db_pool, filters_request_list)
query_parameters[-1] = 'null' if not processed_filters_param else processed_filters_param
# We will output the datasets depending on the includeDatasetResponses parameter
include_dataset = ""
if processed_request.get("includeDatasetResponses"):
include_dataset = processed_request.get("includeDatasetResponses")
else:
include_dataset = "ALL"
LOG.info(f"Query FINAL param: {query_parameters}")
LOG.info('Connecting to the DB to make the query.')
datasets = await get_datasets(db_pool, query_parameters, include_dataset)
LOG.info('Query done.')
# Get the varianstAnnotations handovers and create the object
rsID, cellBase_dict, dbSNP_dict = await fetch_variantAnnotations(processed_request)
variant_annotations = variantAnnotation_object(processed_request, cellBase_dict, dbSNP_dict, {})
# Get the variantId to show it in the resultsHanover section
variantId = list(set([dataset.get("variantId") for dataset in datasets if dataset.get("variantId") != None]))
if len(variantId) > 1:
LOG.debug(f"More than one variantId found: {variantId}. Using just the first one.")
variantId = rsID if not variantId else str(variantId[0])
LOG.debug(f"VariantId: {variantId}")
# Create the query object to show it in the response
query = processed_request.copy()
if query.get("variant"):
query.pop("variant")
# Make lists of the models requests to show it in the response
variant = processed_request.get("variant").split(",") if processed_request.get("variant") else []
variantAnnotation = processed_request.get("variantAnnotation").split(",") if processed_request.get("variantAnnotation") else []
variantMetadata = processed_request.get("variantMetadata").split(",") if processed_request.get("variantMetadata") else []
# We create the final dictionary with all the info we want to return
beacon_response = {
"meta": {
"Variant": ["beacon-variant-v0.1", "ga4gh-variant-representation-v0.1"],
"VariantAnnotation": ["beacon-variant-annotation-v1.0"],
"VariantMetadata": ["beacon-variant-metadata-v1.0"]
},
"value": { 'beaconId': __id__,
'apiVersion': __apiVersion__,
'exists': any([x['exists'] for x in datasets]),
'request': { "meta": { "request": {
"Variant": ["beacon-variant-v0.1"] + variant,
"VariantAnnotation": ["beacon-variant-annotation-v1.0"] + variantAnnotation,
"VariantMetadata": ["beacon-variant-metadata-v1.0"] + variantMetadata
},
"apiVersion": __apiVersion__,
},
"query": query
},
'variantsFound': create_variantsFound(processed_request, filter_exists(processed_request.get("includeDatasetResponses", "NONE"), datasets), variantId, variant_annotations),
'info': None,
'resultsHandover': None,
'beaconHandover': [ { "handoverType" : {
"id" : "CUSTOM",
"label" : "Organization contact"
},
"note" : "Organization contact details maintaining this Beacon",
"url" : "mailto:beacon.ega@crg.eu"
} ]
}
}
# Before returning the response we need to filter it depending on the access levels
beacon_response = {"beconGenomicSnpRequest": beacon_response} # Make sure the key matches the name in the access levels dict
# NOTE we hardcode accessible_datasets and user_levels it because authentication is not implemented yet
accessible_datasets = public_datasets
user_levels = ["PUBLIC"]
filtered_response = filter_response(beacon_response, ACCESS_LEVELS_DICT, accessible_datasets, user_levels, snp2access)
return filtered_response["beconGenomicSnpRequest"]
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Process handling utilities."""
from builtins import object
import os
import subprocess
import tempfile
import threading
import time
import psutil
from base import utils
from metrics import logs
from system import environment
def _end_process(terminate_function, process_result):
"""Ends a running process.
Ignores exceptions.
Args:
process: A subprocess.Popen object.
terminate_function: The function to terminate the process.
process_result: A ProcessResult object where timeout information will be
written to.
"""
try:
terminate_function()
except OSError:
logs.log('Process already killed.')
process_result.timed_out = True
def _wait_process(process,
timeout,
input_data=None,
terminate_before_kill=False,
terminate_wait_time=None):
"""Waits until either the process exits or times out.
Args:
process: A subprocess.Popen object.
timeout: Maximum number of seconds to wait for before sending a signal.
input_data: Input to be sent to the process.
terminate_before_kill: A bool indicating that SIGTERM should be sent to
the process first before SIGKILL (to let the SIGTERM handler run).
terminate_wait_time: Maximum number of seconds to wait for the SIGTERM
handler.
Returns:
A ProcessResult.
"""
result = ProcessResult()
is_windows = environment.platform() == 'WINDOWS'
# On Windows, terminate() just calls Win32 API function TerminateProcess()
# which is equivalent to process kill. So, skip terminate_before_kill.
if terminate_before_kill and not is_windows:
first_timeout_function = process.terminate
# Use a second timer to send the process kill.
second_timer = threading.Timer(timeout + terminate_wait_time, _end_process,
[process.kill, result])
else:
first_timeout_function = process.kill
second_timer = None
first_timer = threading.Timer(timeout, _end_process,
[first_timeout_function, result])
output = None
start_time = time.time()
try:
first_timer.start()
if second_timer:
second_timer.start()
output = process.communicate(input_data)[0]
finally:
first_timer.cancel()
if second_timer:
second_timer.cancel()
result.return_code = process.poll()
result.output = output
result.time_executed = time.time() - start_time
return result
def kill_process_tree(root_pid):
"""Kill process tree."""
try:
parent = psutil.Process(root_pid)
children = parent.children(recursive=True)
except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
logs.log_warn('Failed to find or access process.')
return
for child in children:
try:
child.kill()
except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
logs.log_warn('Failed to kill process child.')
try:
parent.kill()
except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
logs.log_warn('Failed to kill process.')
class ChildProcess(object):
"""A class representing a process that's running."""
def __init__(self, popen, command, max_stdout_len=None, stdout_file=None):
self._popen = popen
self._command = command
self._max_stdout_len = max_stdout_len
self._stdout_file = stdout_file
@property
def command(self):
return self._command
@property
def popen(self):
return self._popen
def communicate(self, input=None): # pylint: disable=redefined-builtin
"""subprocess.Popen.communicate."""
stdout, stderr = self._popen.communicate(input)
if not self._max_stdout_len:
return stdout, stderr
with self._stdout_file:
return utils.read_from_handle_truncated(self._stdout_file,
self._max_stdout_len), stderr
def poll(self):
"""subprocess.Popen.poll."""
return self._popen.poll()
def kill(self):
"""Kills running process and all of its associated children."""
kill_process_tree(self._popen.pid)
def terminate(self):
"""subprocess.Popen.terminate."""
try:
self._popen.terminate()
except OSError:
logs.log_warn('Failed to terminate process.')
class ProcessResult(object):
"""Object representing result of a process execution.
Returned by ProcessRunner.run_and_wait().
Attributes:
command: A list of arguments representing the command line that was run.
return_code: Exit code of the process.
output: Process output.
time_executed: Number of seconds process ran for.
timed_out: Whether or not the process timed out.
"""
def __init__(self,
command=None,
return_code=None,
output=None,
time_executed=None,
timed_out=False):
"""Inits the ProcessResult."""
self.command = command
self.return_code = return_code
self.output = output
self.time_executed = time_executed
self.timed_out = timed_out
class ProcessRunner(object):
"""Generic process runner class.
Attributes:
executable_path: Path to the executable to be run.
default_args: An optional sequence of arguments that are always passed to
the executable when run.
"""
def __init__(self, executable_path, default_args=None):
"""Inits ProcessRunner."""
self._executable_path = executable_path
self._default_args = []
if default_args:
self.default_args.extend(default_args)
@property
def executable_path(self):
return self._executable_path
@property
def default_args(self):
return self._default_args
def get_command(self, additional_args=None):
"""Returns the command line for running the executable.
Args:
additional_args: A sequence of additional arguments to be passed to the
executable.
Returns:
A list containing the command arguments to be passed to subprocess.Popen.
"""
command = [self._executable_path]
command.extend(self._default_args)
if additional_args:
command.extend(additional_args)
return command
def run(self,
additional_args=None,
max_stdout_len=None,
extra_env=None,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
**popen_args):
"""Runs the executable.
Does not block the caller.
Args:
additional_args: A sequence of additional arguments to be passed to the
executable.
max_stdout_len: Optional. Maximum number of bytes to collect in stdout.
extra_env: Optional. A dictionary containing environment variables and
their values. These will be set in the environment of the new process.
stdin: Optional. Passed to subprocess.Popen, defaults to subprocess.PIPE,
stdout: Optional. Passed to subprocess.Popen, defaults to subprocess.PIPE
stderr: Optional. Passed to subprocess.Popen, defaults to
subprocess.STDOUT
**popen_args: Additional arguments that are passed to subprocess.Popen.
Returns:
A subprocess.Popen object for the process.
"""
# TODO: Rename popen_args to popen_kwargs.
command = self.get_command(additional_args)
if stdout == subprocess.PIPE and max_stdout_len:
stdout = tempfile.TemporaryFile()
env = popen_args.pop('env', os.environ.copy())
if extra_env is not None:
env.update(extra_env)
return ChildProcess(
subprocess.Popen(
command,
env=env,
stdin=stdin,
stdout=stdout,
stderr=stderr,
**popen_args),
command,
max_stdout_len=max_stdout_len,
stdout_file=stdout)
# Note: changes to this function may require changes to
# untrusted_runner.proto.
def run_and_wait(self,
additional_args=None,
timeout=None,
terminate_before_kill=False,
terminate_wait_time=None,
input_data=None,
max_stdout_len=None,
extra_env=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
**popen_args):
"""Runs the executable.
Blocks the caller until the process exits.
Args:
additional_args: A sequence of additional arguments to be passed to the
executable.
timeout: Maximum number of seconds to run the process for.
terminate_before_kill: A bool indicating that SIGTERM should be sent to
the process first before SIGKILL (to let the SIGTERM handler run).
terminate_wait_time: Maximum number of seconds to wait for the SIGTERM
handler.
input_data: Optional. A string to be passed as input to the process.
max_stdout_len: Optional. Maximum number of bytes to collect in stdout.
extra_env: Optional. A dictionary containing environment variables and
their values. These will be added to the environment of the new
process.
stdout: Optional. Passed to subprocess.Popen, defaults to subprocess.PIPE
stderr: Optional. Passed to subprocess.Popen, defaults to
subprocess.STDOUT
**popen_args: Additional arguments that are passed to subprocess.Popen.
Returns:
A tuple of (return code, output, time process ran for, or None on timeout)
"""
process = self.run(
additional_args,
max_stdout_len=max_stdout_len,
extra_env=extra_env,
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr,
**popen_args)
start_time = time.time()
if not timeout:
output = process.communicate(input_data)[0]
return ProcessResult(process.command, process.poll(), output,
time.time() - start_time, False)
result = _wait_process(
process,
timeout=timeout,
input_data=input_data,
terminate_before_kill=terminate_before_kill,
terminate_wait_time=terminate_wait_time)
result.command = process.command
return result
|
import numpy as np
import os
distmat_paths = [
'./logs/stage2/resnext101a_384/v1/dist_mat.npy',
'./logs/stage2/resnext101a_384/v2/dist_mat.npy',
'./logs/stage2/101a_384/v1/dist_mat.npy',
'./logs/stage2/101a_384/v2/dist_mat.npy',
'./logs/stage2/101a_384_recrop/v1/dist_mat.npy',
'./logs/stage2/101a_384_recrop/v2/dist_mat.npy',
'./logs/stage2/101a_384_spgan/v1/dist_mat.npy',
'./logs/stage2/101a_384_spgan/v2/dist_mat.npy',
'./logs/stage2/densenet169a_384/v1/dist_mat.npy',
'./logs/stage2/densenet169a_384/v2/dist_mat.npy',
'./logs/stage2/s101_384/v1/dist_mat.npy',
'./logs/stage2/s101_384/v2/dist_mat.npy',
'./logs/stage2/se_resnet101a_384/v1/dist_mat.npy',
'./logs/stage2/se_resnet101a_384/v2/dist_mat.npy',
'./logs/stage2/transreid_256/v1/dist_mat.npy',
'./logs/stage2/transreid_256/v2/dist_mat.npy',
]
distmat = np.zeros((1103,31238))
for i in distmat_paths:
distmat += np.load(i)
sort_distmat_index = np.argsort(distmat, axis=1)
print(sort_distmat_index)
print('The shape of distmat is: {}'.format(distmat.shape))
save_path = './track2.txt'
with open(save_path,'w') as f:
for item in sort_distmat_index:
for i in range(99):
f.write(str(item[i] + 1) + ' ')
f.write(str(item[99] + 1) + '\n')
|
"""
An implementation of JSON Schema for Python
The main functionality is provided by the validator classes for each of the
supported JSON Schema versions.
Most commonly, the :function:`validate` function is the quickest way to simply
validate a given instance under a schema, and will create a validator for you.
"""
from __future__ import division, unicode_literals
import collections
import itertools
import operator
import re
import sys
import warnings
__version__ = "0.7"
FLOAT_TOLERANCE = 10 ** -15
PY3 = sys.version_info[0] >= 3
if PY3:
basestring = unicode = str
iteritems = operator.methodcaller("items")
from urllib.parse import unquote
else:
from itertools import izip as zip
iteritems = operator.methodcaller("iteritems")
from urllib import unquote
class UnknownType(Exception):
"""
An unknown type was given.
"""
class InvalidRef(Exception):
"""
An invalid reference was given.
"""
class SchemaError(Exception):
"""
The provided schema is malformed.
The same attributes exist for ``SchemaError``s as for ``ValidationError``s.
"""
validator = None
def __init__(self, message):
super(SchemaError, self).__init__(message)
self.message = message
self.path = []
class ValidationError(Exception):
"""
The instance didn't properly validate with the provided schema.
Relevant attributes are:
* ``message`` : a human readable message explaining the error
* ``path`` : a list containing the path to the offending element (or []
if the error happened globally) in *reverse* order (i.e.
deepest index first).
"""
# the failing validator will be set externally at whatever recursion level
# is immediately above the validation failure
validator = None
def __init__(self, message):
super(ValidationError, self).__init__(message)
self.message = message
# Any validator that recurses must append to the ValidationError's
# path (e.g., properties and items)
self.path = []
class Draft3Validator(object):
"""
A validator for JSON Schema draft 3.
"""
DEFAULT_TYPES = {
"array" : list, "boolean" : bool, "integer" : int, "null" : type(None),
"number" : (int, float), "object" : dict, "string" : basestring,
}
def __init__(self, schema, types=()):
"""
Initialize a validator.
``schema`` should be a *valid* JSON Schema object already converted to
a native Python object (typically a dict via ``json.load``).
``types`` is a mapping (or iterable of 2-tuples) containing additional
types or alternate types to verify via the 'type' property. For
instance, the default types for the 'number' JSON Schema type are
``int`` and ``float``. To override this behavior (e.g. for also
allowing ``decimal.Decimal``), pass ``types={"number" : (int, float,
decimal.Decimal)} *including* the default types if so desired, which
are fairly obvious but can be accessed via the ``DEFAULT_TYPES``
attribute on this class if necessary.
"""
self._types = dict(self.DEFAULT_TYPES)
self._types.update(types)
self._types["any"] = tuple(self._types.values())
self.schema = schema
def is_type(self, instance, type):
"""
Check if an ``instance`` is of the provided (JSON Schema) ``type``.
"""
if type not in self._types:
raise UnknownType(type)
type = self._types[type]
# bool inherits from int, so ensure bools aren't reported as integers
if isinstance(instance, bool):
type = _flatten(type)
if int in type and bool not in type:
return False
return isinstance(instance, type)
def is_valid(self, instance, _schema=None):
"""
Check if the ``instance`` is valid under the current schema.
Returns a bool indicating whether validation succeeded.
"""
error = next(self.iter_errors(instance, _schema), None)
return error is None
@classmethod
def check_schema(cls, schema):
"""
Validate a ``schema`` against the meta-schema to see if it is valid.
"""
for error in cls(cls.META_SCHEMA).iter_errors(schema):
s = SchemaError(error.message)
s.path = error.path
s.validator = error.validator
# I think we're safer raising these always, not yielding them
raise s
def iter_errors(self, instance, _schema=None):
"""
Lazily yield each of the errors in the given ``instance``.
"""
if _schema is None:
_schema = self.schema
for k, v in iteritems(_schema):
validator = getattr(self, "validate_%s" % (k.lstrip("$"),), None)
if validator is None:
continue
errors = validator(v, instance, _schema) or ()
for error in errors:
# if the validator hasn't already been set (due to recursion)
# make sure to set it
error.validator = error.validator or k
yield error
def validate(self, *args, **kwargs):
"""
Validate an ``instance`` under the given ``schema``.
"""
for error in self.iter_errors(*args, **kwargs):
raise error
def validate_type(self, types, instance, schema):
types = _list(types)
for type in types:
# Ouch. Brain hurts. Two paths here, either we have a schema, then
# check if the instance is valid under it
if ((
self.is_type(type, "object") and
self.is_valid(instance, type)
# Or we have a type as a string, just check if the instance is that
# type. Also, HACK: we can reach the `or` here if skip_types is
# something other than error. If so, bail out.
) or (
self.is_type(type, "string") and
(self.is_type(instance, type) or type not in self._types)
)):
return
else:
yield ValidationError(_types_msg(instance, types))
def validate_properties(self, properties, instance, schema):
if not self.is_type(instance, "object"):
return
for property, subschema in iteritems(properties):
if property in instance:
for error in self.iter_errors(instance[property], subschema):
error.path.append(property)
yield error
elif subschema.get("required", False):
error = ValidationError(
"%r is a required property" % (property,)
)
error.path.append(property)
error.validator = "required"
yield error
def validate_patternProperties(self, patternProperties, instance, schema):
for pattern, subschema in iteritems(patternProperties):
for k, v in iteritems(instance):
if re.match(pattern, k):
for error in self.iter_errors(v, subschema):
yield error
def validate_additionalProperties(self, aP, instance, schema):
if not self.is_type(instance, "object"):
return
extras = set(_find_additional_properties(instance, schema))
if self.is_type(aP, "object"):
for extra in extras:
for error in self.iter_errors(instance[extra], aP):
yield error
elif not aP and extras:
error = "Additional properties are not allowed (%s %s unexpected)"
yield ValidationError(error % _extras_msg(extras))
def validate_dependencies(self, dependencies, instance, schema):
if not self.is_type(instance, "object"):
return
for property, dependency in iteritems(dependencies):
if property not in instance:
continue
if self.is_type(dependency, "object"):
for error in self.iter_errors(instance, dependency):
yield error
else:
dependencies = _list(dependency)
for dependency in dependencies:
if dependency not in instance:
yield ValidationError(
"%r is a dependency of %r" % (dependency, property)
)
def validate_items(self, items, instance, schema):
if not self.is_type(instance, "array"):
return
if self.is_type(items, "object"):
for index, item in enumerate(instance):
for error in self.iter_errors(item, items):
error.path.append(index)
yield error
else:
for (index, item), subschema in zip(enumerate(instance), items):
for error in self.iter_errors(item, subschema):
error.path.append(index)
yield error
def validate_additionalItems(self, aI, instance, schema):
if not self.is_type(instance, "array"):
return
if not self.is_type(schema.get("items"), "array"):
return
if self.is_type(aI, "object"):
for item in instance[len(schema):]:
for error in self.iter_errors(item, aI):
yield error
elif not aI and len(instance) > len(schema.get("items", [])):
error = "Additional items are not allowed (%s %s unexpected)"
yield ValidationError(
error % _extras_msg(instance[len(schema.get("items", [])):])
)
def validate_minimum(self, minimum, instance, schema):
if not self.is_type(instance, "number"):
return
instance = float(instance)
if schema.get("exclusiveMinimum", False):
failed = instance <= minimum
cmp = "less than or equal to"
else:
failed = instance < minimum
cmp = "less than"
if failed:
yield ValidationError(
"%r is %s the minimum of %r" % (instance, cmp, minimum)
)
def validate_maximum(self, maximum, instance, schema):
if not self.is_type(instance, "number"):
return
instance = float(instance)
if schema.get("exclusiveMaximum", False):
failed = instance >= maximum
cmp = "greater than or equal to"
else:
failed = instance > maximum
cmp = "greater than"
if failed:
yield ValidationError(
"%r is %s the maximum of %r" % (instance, cmp, maximum)
)
def validate_minItems(self, mI, instance, schema):
if self.is_type(instance, "array") and len(instance) < mI:
yield ValidationError("%r is too short" % (instance,))
def validate_maxItems(self, mI, instance, schema):
if self.is_type(instance, "array") and len(instance) > mI:
yield ValidationError("%r is too long" % (instance,))
def validate_uniqueItems(self, uI, instance, schema):
if uI and self.is_type(instance, "array") and not _uniq(instance):
yield ValidationError("%r has non-unique elements" % instance)
def validate_pattern(self, patrn, instance, schema):
if self.is_type(instance, "string") and not re.match(patrn, instance):
yield ValidationError("%r does not match %r" % (instance, patrn))
def validate_minLength(self, mL, instance, schema):
if self.is_type(instance, "string") and len(instance) < mL:
yield ValidationError("%r is too short" % (instance,))
def validate_maxLength(self, mL, instance, schema):
if self.is_type(instance, "string") and len(instance) > mL:
yield ValidationError("%r is too long" % (instance,))
def validate_enum(self, enums, instance, schema):
if instance not in enums:
yield ValidationError("%r is not one of %r" % (instance, enums))
def validate_divisibleBy(self, dB, instance, schema):
if not self.is_type(instance, "number"):
return
if isinstance(dB, float):
mod = instance % dB
failed = (mod > FLOAT_TOLERANCE) and (dB - mod) > FLOAT_TOLERANCE
else:
failed = instance % dB
if failed:
yield ValidationError("%r is not divisible by %r" % (instance, dB))
def validate_disallow(self, disallow, instance, schema):
for disallowed in _list(disallow):
if self.is_valid(instance, {"type" : [disallowed]}):
yield ValidationError(
"%r is disallowed for %r" % (disallowed, instance)
)
def validate_extends(self, extends, instance, schema):
if self.is_type(extends, "object"):
extends = [extends]
for subschema in extends:
for error in self.iter_errors(instance, subschema):
yield error
def validate_ref(self, ref, instance, schema):
if ref != "#" and not ref.startswith("#/"):
warnings.warn("jsonschema only supports json-pointer $refs")
return
resolved = resolve_json_pointer(self.schema, ref)
for error in self.iter_errors(instance, resolved):
yield error
Draft3Validator.META_SCHEMA = {
"$schema" : "http://json-schema.org/draft-03/schema#",
"id" : "http://json-schema.org/draft-03/schema#",
"type" : "object",
"properties" : {
"type" : {
"type" : ["string", "array"],
"items" : {"type" : ["string", {"$ref" : "#"}]},
"uniqueItems" : True,
"default" : "any"
},
"properties" : {
"type" : "object",
"additionalProperties" : {"$ref" : "#", "type": "object"},
"default" : {}
},
"patternProperties" : {
"type" : "object",
"additionalProperties" : {"$ref" : "#"},
"default" : {}
},
"additionalProperties" : {
"type" : [{"$ref" : "#"}, "boolean"], "default" : {}
},
"items" : {
"type" : [{"$ref" : "#"}, "array"],
"items" : {"$ref" : "#"},
"default" : {}
},
"additionalItems" : {
"type" : [{"$ref" : "#"}, "boolean"], "default" : {}
},
"required" : {"type" : "boolean", "default" : False},
"dependencies" : {
"type" : ["string", "array", "object"],
"additionalProperties" : {
"type" : ["string", "array", {"$ref" : "#"}],
"items" : {"type" : "string"}
},
"default" : {}
},
"minimum" : {"type" : "number"},
"maximum" : {"type" : "number"},
"exclusiveMinimum" : {"type" : "boolean", "default" : False},
"exclusiveMaximum" : {"type" : "boolean", "default" : False},
"minItems" : {"type" : "integer", "minimum" : 0, "default" : 0},
"maxItems" : {"type" : "integer", "minimum" : 0},
"uniqueItems" : {"type" : "boolean", "default" : False},
"pattern" : {"type" : "string", "format" : "regex"},
"minLength" : {"type" : "integer", "minimum" : 0, "default" : 0},
"maxLength" : {"type" : "integer"},
"enum" : {"type" : "array", "minItems" : 1, "uniqueItems" : True},
"default" : {"type" : "any"},
"title" : {"type" : "string"},
"description" : {"type" : "string"},
"format" : {"type" : "string"},
"maxDecimal" : {"type" : "number", "minimum" : 0},
"divisibleBy" : {
"type" : "number",
"minimum" : 0,
"exclusiveMinimum" : True,
"default" : 1
},
"disallow" : {
"type" : ["string", "array"],
"items" : {"type" : ["string", {"$ref" : "#"}]},
"uniqueItems" : True
},
"extends" : {
"type" : [{"$ref" : "#"}, "array"],
"items" : {"$ref" : "#"},
"default" : {}
},
"id" : {"type" : "string", "format" : "uri"},
"$ref" : {"type" : "string", "format" : "uri"},
"$schema" : {"type" : "string", "format" : "uri"},
},
"dependencies" : {
"exclusiveMinimum" : "minimum", "exclusiveMaximum" : "maximum"
},
}
class Validator(Draft3Validator):
"""
Deprecated: Use :class:`Draft3Validator` instead.
"""
def __init__(
self, version=None, unknown_type="skip", unknown_property="skip",
*args, **kwargs
):
super(Validator, self).__init__({}, *args, **kwargs)
warnings.warn(
"Validator is deprecated and will be removed. "
"Use Draft3Validator instead.",
DeprecationWarning, stacklevel=2,
)
class ErrorTree(object):
"""
ErrorTrees make it easier to check which validations failed.
"""
def __init__(self, errors=()):
self.errors = {}
self._contents = collections.defaultdict(self.__class__)
for error in errors:
container = self
for element in reversed(error.path):
container = container[element]
container.errors[error.validator] = error
def __contains__(self, k):
return k in self._contents
def __getitem__(self, k):
return self._contents[k]
def __setitem__(self, k, v):
self._contents[k] = v
def __iter__(self):
return iter(self._contents)
def __len__(self):
child_errors = sum(len(tree) for _, tree in iteritems(self._contents))
return len(self.errors) + child_errors
def __repr__(self):
return "<%s (%s errors)>" % (self.__class__.__name__, len(self))
def resolve_json_pointer(schema, ref):
"""
Resolve a local reference ``ref`` within the given root ``schema``.
``ref`` should be a local ref whose ``#`` is still present.
"""
if ref == "#":
return schema
parts = ref.lstrip("#/").split("/")
parts = map(unquote, parts)
parts = [part.replace('~1', '/').replace('~0', '~') for part in parts]
try:
for part in parts:
schema = schema[part]
except KeyError:
raise InvalidRef("Unresolvable json-pointer %r" % ref)
else:
return schema
def _find_additional_properties(instance, schema):
"""
Return the set of additional properties for the given ``instance``.
Weeds out properties that should have been validated by ``properties`` and
/ or ``patternProperties``.
Assumes ``instance`` is dict-like already.
"""
properties = schema.get("properties", {})
patterns = "|".join(schema.get("patternProperties", {}))
for property in instance:
if property not in properties:
if patterns and re.search(patterns, property):
continue
yield property
def _extras_msg(extras):
"""
Create an error message for extra items or properties.
"""
if len(extras) == 1:
verb = "was"
else:
verb = "were"
return ", ".join(repr(extra) for extra in extras), verb
def _types_msg(instance, types):
"""
Create an error message for a failure to match the given types.
If the ``instance`` is an object and contains a ``name`` property, it will
be considered to be a description of that object and used as its type.
Otherwise the message is simply the reprs of the given ``types``.
"""
reprs = []
for type in types:
try:
reprs.append(repr(type["name"]))
except Exception:
reprs.append(repr(type))
return "%r is not of type %s" % (instance, ", ".join(reprs))
def _flatten(suitable_for_isinstance):
"""
isinstance() can accept a bunch of really annoying different types:
* a single type
* a tuple of types
* an arbitrary nested tree of tuples
Return a flattened tuple of the given argument.
"""
types = set()
if not isinstance(suitable_for_isinstance, tuple):
suitable_for_isinstance = (suitable_for_isinstance,)
for thing in suitable_for_isinstance:
if isinstance(thing, tuple):
types.update(_flatten(thing))
else:
types.add(thing)
return tuple(types)
def _list(thing):
"""
Wrap ``thing`` in a list if it's a single str.
Otherwise, return it unchanged.
"""
if isinstance(thing, basestring):
return [thing]
return thing
def _delist(thing):
"""
Unwrap ``thing`` to a single element if its a single str in a list.
Otherwise, return it unchanged.
"""
if (
isinstance(thing, list) and
len(thing) == 1
and isinstance(thing[0], basestring)
):
return thing[0]
return thing
def _uniq(container):
"""
Check if all of a container's elements are unique.
Successively tries first to rely that the elements are hashable, then
falls back on them being sortable, and finally falls back on brute
force.
"""
try:
return len(set(container)) == len(container)
except TypeError:
try:
sort = sorted(container)
sliced = itertools.islice(container, 1, None)
for i, j in zip(container, sliced):
if i == j:
return False
except (NotImplementedError, TypeError):
seen = []
for e in container:
if e in seen:
return False
seen.append(e)
return True
def validate(instance, schema, cls=Draft3Validator, *args, **kwargs):
"""
Validate an ``instance`` under the given ``schema``.
First verifies that the provided schema is itself valid, since not doing so
can lead to less obvious failures when validating. If you know it is or
don't care, use ``YourValidator(schema).validate(instance)`` directly
instead (e.g. ``Draft3Validator``).
``cls`` is a validator class that will be used to validate the instance.
By default this is a draft 3 validator. Any other provided positional and
keyword arguments will be provided to this class when constructing a
validator.
"""
meta_validate = kwargs.pop("meta_validate", None)
if meta_validate is not None:
warnings.warn(
"meta_validate is deprecated and will be removed. If you do not "
"want to validate a schema, use Draft3Validator.validate instead.",
DeprecationWarning, stacklevel=2,
)
if meta_validate is not False: # yes this is needed since True was default
cls.check_schema(schema)
cls(schema, *args, **kwargs).validate(instance)
|
/******************************************************************************
*** The driver code of an example of how to use the INHDF5 API
***
*** Copyright (c) 2020 Ioannis Nompelis
*** Ioannis Nompelis <nompelis@nobelware.com>
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mpi.h>
#include <hdf5.h>
#include "inUtils_HDF5.h"
int main( int argc, char *argv[] )
{
int ierr=0;
int irank,nrank;
MPI_Comm comm;
hid_t id_alist, id_file, id_grp, id_data;
hid_t id_type, id_space;
hsize_t idims[1],ioff[1],icnt[1];
int* idum;
int n;
//-- start the day with MPI
MPI_Init( &argc, &argv );
MPI_Comm_dup( MPI_COMM_WORLD, &comm );
MPI_Comm_rank( comm, &irank );
MPI_Comm_size( comm, &nrank );
if( nrank > 2 ) {
printf("This demo is meant to run with 2 processes \n");
MPI_Finalize();
return 1;
}
//-- open the HDF5 API
H5open();
// create a file
ierr = inUtils_HDF_CreateFile( "test_file", comm, &id_alist, &id_file );
if( ierr == 0 ) if( irank == 0 ) printf("File creation success\n");
// close the file to subsequently test the opening of a file
ierr = inUtils_HDF_CloseFile( comm, &id_alist, &id_file );
if( ierr == 0 ) if( irank == 0 ) printf("File closing success\n");
// open a file
ierr = inUtils_HDF_OpenFile( "test_file", comm, &id_alist, &id_file );
if( ierr == 0 ) if( irank == 0 ) printf("File opening success\n");
// create a group
ierr = inUtils_HDF_CreateGroup( "my_group", comm, id_file, &id_grp );
if( ierr == 0 ) if( irank == 0 ) printf("Group creation success\n");
// close this group the test subsequent opening of the group
ierr = inUtils_HDF_CloseGroup( comm, &id_grp );
if( ierr == 0 ) if( irank == 0 ) printf("Group closing success\n");
// open a group
ierr = inUtils_HDF_OpenGroup( "my_group", comm, id_file, &id_grp );
if( ierr == 0 ) if( irank == 0 ) printf("Group opening success\n");
// create a dataspace (to use in creating a dataset)
idims[0] = 20;
id_space = H5Screate_simple( 1, idims, idims );
// create a dataset
id_type = H5T_NATIVE_INT;
ierr = inUtils_HDF_CreateDataset( "my_dataset", comm, id_grp,
id_type, id_space,
&id_data );
if( ierr == 0 ) if( irank == 0 ) printf("Dataset creation success\n");
// close the dataset so that we can test the re-opening
ierr = inUtils_HDF_CloseDataset( comm, &id_data );
if( ierr == 0 ) if( irank == 0 ) printf("Dataset closing success\n");
// close the space that is no longer needed
H5Sclose( id_space );
// open a dataset
ierr = inUtils_HDF_OpenDataset( "my_dataset", comm, id_grp,
&id_data, &id_type, &id_space );
if( ierr == 0 ) if( irank == 0 ) printf("Dataset opening success\n");
// create an array to write to the dataset
idum = (int*) malloc( 10 * sizeof(int) ); // no error-trapping
for(n=0;n<10;++n) idum[n] = irank + 1;
// write to the dataset
if( irank == 0 ) ioff[0] = 0;
if( irank == 1 ) ioff[0] = 10;
icnt[0] = 10;
ierr = inUtils_HDF_DatasetWrite( comm, id_data, id_type, id_space,
1, ioff, icnt, idum );
if( ierr == 0 ) if( irank == 0 ) printf("Write to dataset successful\n");
// close the dataset so that we can test the re-opening and re-reading
ierr = inUtils_HDF_CloseDataset( comm, &id_data );
if( ierr == 0 ) if( irank == 0 ) printf("Dataset closing success\n");
// close the space
H5Sclose( id_space );
// change the stored data to something other than what we will read
for(n=0;n<10;++n) idum[n] = irank + 1;
// open the dataset so that we can test reading
ierr = inUtils_HDF_OpenDataset( "my_dataset", comm, id_grp,
&id_data, &id_type, &id_space );
if( ierr == 0 ) if( irank == 0 ) printf("Dataset opening success\n");
// read the dataset
if( irank == 0 ) ioff[0] = 0;
if( irank == 1 ) ioff[0] = 10;
icnt[0] = 10;
ierr = inUtils_HDF_DatasetRead( comm, id_data, id_type, id_space,
1, ioff, icnt, idum );
if( ierr == 0 ) if( irank == 0 ) printf("Reading from dataset successful\n");
// close the dataset for doog
ierr = inUtils_HDF_CloseDataset( comm, &id_data );
if( ierr == 0 ) if( irank == 0 ) printf("Dataset closing success\n");
// close the space
H5Sclose( id_space );
// show the contents of the buffer as we read it
if( irank == 0 ) {
printf(" Rank 0 data: ");
for(n=0;n<10;++n) printf(" %d",idum[n]);
printf(" \n");
sleep(1);
MPI_Barrier( comm );
} else {
MPI_Barrier( comm );
printf(" Rank 1 data: ");
for(n=0;n<10;++n) printf(" %d",idum[n]);
printf(" \n");
sleep(1);
}
// drop buffer
free( idum );
printf("Final termination \n");
ierr = inUtils_HDF_CloseGroup( comm, &id_grp );
ierr = inUtils_HDF_CloseFile( comm, &id_alist, &id_file );
//-- close the HDF5 and MPI APIs
H5close();
MPI_Finalize();
return 0;
}
|
import shutil
import unittest
import tempfile
import pandas as pd
from kgtk.cli_entry import cli_entry
from kgtk.exceptions import KGTKException
class TestKGTKNormalizeNodes(unittest.TestCase):
def setUp(self) -> None:
self.file_path = 'data/sample_kgtk_nodes.tsv'
self.temp_dir = tempfile.mkdtemp()
def tearDown(self) -> None:
shutil.rmtree(self.temp_dir)
def test_kgtk_normalize_nodes_default(self):
cli_entry("kgtk", "normalize-nodes", "-i", self.file_path, "-o", f'{self.temp_dir}/normalize.tsv', "--verbose",
"--show-option")
df = pd.read_csv(f'{self.temp_dir}/normalize.tsv', sep='\t')
self.assertEqual(len(df), 52)
df = df.loc[df['node1'] == 'Q183'].loc[df['label'] == 'label']
self.assertTrue(len(df), 3)
print(df)
labels = list(df['node2'].unique())
self.assertTrue("'Germany'@en" in labels)
self.assertTrue("'Германия'@ru" in labels)
self.assertTrue("'Німеччина'@uk" in labels)
def test_kgtk_normalize_nodes_alias_only(self):
cli_entry("kgtk", "normalize-nodes", "-i", self.file_path, "-o", f'{self.temp_dir}/normalize.tsv', "-c",
"alias")
df = pd.read_csv(f'{self.temp_dir}/normalize.tsv', sep='\t')
self.assertEqual(len(df), 24)
self.assertEqual(list(df['label'].unique())[0], 'alias')
def test_kgtk_normalize_nodes_alias_only_labels(self):
cli_entry("kgtk", "normalize-nodes", "-i", self.file_path, "-o", f'{self.temp_dir}/normalize.tsv', "-c",
"alias", "--labels", "aliases")
df = pd.read_csv(f'{self.temp_dir}/normalize.tsv', sep='\t')
self.assertEqual(len(df), 24)
self.assertEqual(list(df['label'].unique())[0], 'aliases')
|
from gensim.corpora.dictionary import Dictionary
from gensim.models.coherencemodel import CoherenceModel
from gensim.matutils import Sparse2Corpus
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
import torch
from torch.optim import Adam
from torch.utils.data.sampler import WeightedRandomSampler
from ptavitm.model import train, predict
from ptavitm.vae import ProdLDA
from ptavitm.utils import CountTensorDataset
# TODO decide how a partial_fit method API might work and implement, also more thought into score and logging
class ProdLDATransformer(TransformerMixin, BaseEstimator):
def __init__(
self,
cuda=None,
batch_size=200,
epochs=80,
hidden1_dimension=100,
hidden2_dimension=100,
topics=50,
lr=0.001,
samples=20000,
score_num=7,
score_type="coherence",
) -> None:
self.cuda = torch.cuda.is_available() if cuda is None else cuda
self.batch_size = batch_size
self.epochs = epochs
self.hidden1_dimension = hidden1_dimension
self.hidden2_dimension = hidden2_dimension
self.topics = topics
self.lr = lr
self.samples = samples
self.autoencoder = None
self.score_type = score_type
self.score_num = score_num
if self.score_type not in ["coherence"]:
raise ValueError('score_type must be "coherence"')
def fit(self, X, y=None) -> None:
documents, features = X.shape
ds = CountTensorDataset(X.astype(np.float32))
self.autoencoder = ProdLDA(
in_dimension=features,
hidden1_dimension=self.hidden1_dimension,
hidden2_dimension=self.hidden2_dimension,
topics=self.topics,
)
if self.cuda:
self.autoencoder.cuda()
ae_optimizer = Adam(
self.autoencoder.parameters(), lr=self.lr, betas=(0.99, 0.999)
)
train(
ds,
self.autoencoder,
cuda=self.cuda,
validation=None,
epochs=self.epochs,
batch_size=self.batch_size,
optimizer=ae_optimizer,
sampler=WeightedRandomSampler(
torch.ones(documents), min(documents, self.samples)
),
silent=True,
num_workers=0, # TODO causes a bug to change this on Mac
)
def transform(self, X):
if self.autoencoder is None:
raise NotFittedError
self.autoencoder.eval()
ds = CountTensorDataset(X.astype(np.float32))
output = predict(
ds,
self.autoencoder,
cuda=self.cuda,
encode=True,
silent=True,
batch_size=self.batch_size,
num_workers=0, # TODO causes a bug to change this on Mac
)
return output.cpu().numpy()
def score(self, X, y=None, sample_weight=None) -> float:
# TODO this needs further testing for correctness, WIP
if self.autoencoder is None:
raise NotFittedError
self.autoencoder.eval()
corpus = Sparse2Corpus(X, documents_columns=False)
decoder_weight = self.autoencoder.decoder.linear.weight.detach().cpu()
id2word = {index: str(index) for index in range(X.shape[1])}
topics = [
[str(item.item()) for item in topic]
for topic in decoder_weight.topk(min(self.score_num, X.shape[1]), dim=0)[
1
].t()
]
cm = CoherenceModel(
topics=topics,
corpus=corpus,
dictionary=Dictionary.from_corpus(corpus, id2word),
coherence="u_mass",
)
return cm.get_coherence()
|
#coding:utf-8
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with cls._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = object.__new__(cls)
cls._instance.__Singleton_Init__(*args, **kwargs)
return cls._instance
def __Singleton_Init__(self):
raise RuntimeError("__Singleton_Init__ must be overwritten")
|
from enum import Enum
class NumeroCarta(Enum):
NINGUNO = 0
AS = 1
DOS = 2
TRES = 3
CUATRO = 4
CINCO = 5
SEIS = 6
SIETE = 7
OCHO = 8
NUEVE = 9
DIEZ = 10
JACK = 11
QUEEN = 12
KING = 13
class PintaCarta(Enum):
NINGUNO = 0
TREBOL = 1
PICA = 2
CORAZON = 3
DIAMANTE = 4
class GrupoCarta(Enum):
NINGUNA = 0
NON = 1
PAR = 2
TERNA = 3
CUARTA = 4
QUINTA = 5
SEXTA = 6
SEPTIMA = 7
OCTAVA = 8
NOVENA = 9
DECIMA = 10
|
// DO NOT EDIT! This test has been generated by tools/gentest.py.
// OffscreenCanvas test in a worker:2d.fillStyle.parse.hex6
// Description:
// Note:<p class="notes">
importScripts("/resources/testharness.js");
importScripts("/2dcontext/resources/canvas-tests.js");
var t = async_test("");
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.fillStyle = '#00fF00';
ctx.fillRect(0, 0, 100, 50);
_assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255");
t.done();
});
done();
|